Method to Transform XML using xslt and save to target XML
This method transforms a given xml file using the provided xslt into another xml file and save it in the specified target file.
This method transforms a given xml file using the provided xslt into another xml file and save it in the specified target file. Namespaces
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.IO;
using System.Text; The Method
///
/// Method to transform XML to another format using xslt file
///
///
///
///
private void Transform(string resultFileName, string orgXMLFile, string xsltFile)
{
string resultDoc = Server.MapPath(resultFileName);
string xmlPath = Server.MapPath(orgXMLFile);
string xslPath = Server.MapPath(xsltFile);
XmlTextWriter writer = null;
StreamReader reader = null;
XmlTextReader xmlReader = null;
FileStream fs = null;
XPathDocument doc = null;
XslCompiledTransform xslDoc = null;
try
{
//Create a file stream to read the XML file to be transformed
fs = new FileStream(xmlPath, FileMode.Open,FileAccess.Read);
reader = new StreamReader(fs, Encoding.UTF8);
//Load the file to XML reader
xmlReader = new XmlTextReader(reader);
//Instantiate the XPathDocument Class
doc = new XPathDocument(xmlReader);
//create a XML text writer for the target xml file which will contain the transformed XML
writer = new XmlTextWriter(resultDoc, null);
//Instantiate the XslTransform Class
xslDoc = new XslCompiledTransform();
//Load the XSLT
xslDoc.Load(xslPath);
//Transform
xslDoc.Transform(doc, null, writer);
//Close Readers and writers
writer.Close();
reader.Close();
xmlReader.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
writer = null;
reader = null;
xmlReader = null;
fs = null;
xslDoc = null;
doc = null;
}
}