Using XSLT Stylesheets with C#
This guide demonstrates how to leverage the power of XSLT stylesheets to transform XML data within your C# applications. The process involves loading the XML document and XSLT stylesheet, then applying the transformation to generate the desired output.
Steps:
XML Document Loading: Load your XML document using the XPathDocument
class. This provides efficient access to the XML data.
XSLT Stylesheet Loading: Instantiate an XslTransform
(or the more performant XslCompiledTransform
) object and load your XSLT stylesheet using the Load()
method.
Output Stream Creation: Create an XmlTextWriter
to specify the output file and format (e.g., HTML, XML).
Transformation Execution: Execute the transformation using the Transform()
method. This method takes the XML document, optional parameters, and the output writer as arguments.
Code Example (using XslTransform):
<code class="language-csharp">XPathDocument xmlDoc = new XPathDocument(xmlFilePath); XslTransform xslt = new XslTransform(); xslt.Load(xsltFilePath); XmlTextWriter writer = new XmlTextWriter(outputFilePath, null); xslt.Transform(xmlDoc, null, writer);</code>
Code Example (using XslCompiledTransform for enhanced performance):
<code class="language-csharp">XPathDocument xmlDoc = new XPathDocument(xmlFilePath); XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(xsltFilePath); XmlTextWriter writer = new XmlTextWriter(outputFilePath, null); xslt.Transform(xmlDoc, null, writer);</code>
Remember to replace xmlFilePath
, xsltFilePath
, and outputFilePath
with the actual paths to your files. The XslCompiledTransform
class offers performance benefits through caching and JIT compilation, making it preferable for production environments. Using these steps, you can seamlessly integrate XSLT transformations into your C# projects.
The above is the detailed content of How to Apply XSLT Stylesheets to XML Documents in C#?. For more information, please follow other related articles on the PHP Chinese website!