Welcome to MSDN Blogs Sign in | Join | Help

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!

Published Wednesday, November 01, 2006 4:17 PM by Aaron Dunnington
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Working with Strings of XML and XSL

what about if you want to have <xsl: includes> how would you create a resolver of something for it

arthur.boudreau@servicecanada.gc.ca

Friday, July 06, 2007 2:52 PM by Arthur

# re: Working with Strings of XML and XSL

what about if you want to have <xsl: includes> how would you create a resolver of something for it

Saturday, October 06, 2007 1:37 PM by markovich

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker