Working with Strings of XML and XSL
Recently, there have been a few posts on the .NET XML Forums concerning the usage of XML and XSL strings rather than streams.
Thus, I thought I'd share a snippet of how this type of transformation can be applied using .NET.
Working with Strings of XML and XSL
// XML and XSL content strings
string xmlContent = "YOUR_XML_HERE";
string xslContent = "YOUR_XSL_HERE";
// Load the source XML into an XmlDocument with LoadXml
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlContent);
// Load the XSL with an XmlReader attached to a StringReader
XslCompiledTransform transformer = new XslCompiledTransform();
transformer.Load(new XmlTextReader(new StringReader(xslContent)));
// Create a writer for the result of the transformation
StringWriter writer = new StringWriter();
// Perform the transform
transformer.Transform(xmlDoc, null, writer);
// Write the result of the transformation
Console.WriteLine(writer.ToString());
To summarize, this code does the following:
- Defines string variables for the XML and XSL
- Creates an XmlDocument around the XML string
- Creates an XslCompiledTransform around the XSL string
- Applies the transformation
- Writes the transform result string
In the context of this example, the transformation result could have been written to the console output stream directly. However, for this example, the StringWriter demonstrates how to access the transformation result as a string rather than a stream. Likewise, the XmlDocument can be loaded with a stream rather than a string.
If you have any questions or comments, please don't hesitate to send me feedback!