Using XSLT in .Net
So you’ve finished writing your new XSLT file using your favorite XML/XSLT editing tool. Great. Now for the next problem, you’ve been given the task to transform thousands of XML documents using your new XSLT file. Great… There’s no way we can transform all of these documents by hand. At this point we should be thinking about automating this process in the fastest and most efficient way possible. This scenario may sound familiar to some of us. Luckily, .Net provides us with such options.
For this example we’ll be serializing an XML file and transforming it using .Net’s XSLT processor. The process is very simple, and requires very little code.
- Load the XML File into memory using the XmlReader class.
var reader = XmlReader.Create(xmlFileLocation);
- Create a StreamWriter object which will be used to write the transformation to a file.
var textWriter = new StreamWriter(outputFileLocation);
- Create an XslCompiledTransform object which will be used to transform the XML file using the specified XSLT file.
var xslTransform = new XslCompiledTransform();
- Transform the XML and write to a file using the StreamWriter.
xslTransform.Load(xsltFileLocation); xslTransform.Transform(reader, null, textWriter);
Hope this helps.