Working with a Stylesheet Programmatically

The real magic of XSLT in .NET comes from the fact that an XSLT stylesheet is just an XML document; therefore, you can create and manipulate the stylesheet just like any other XML document, using the tools you’re already familiar with.

Creating a stylesheet

Example 7-8 shows a program that creates the stylesheet in Example 7-1 using XmlWriter. It’s fairly straightforward, so I’ll let the code speak for itself.

Example 7-8. Creating a stylesheet programmatically
using System; using System.IO; using System.Xml; using System.Xml.Xsl; public class CreateStylesheet { private const string ns = ""; public static void Main(string [ ] args) { XmlTextWriter writer = new XmlTextWriter(Console.Out); writer.Formatting = Formatting.Indented; writer.WriteStartDocument( ); writer.WriteStartElement("xsl","stylesheet",ns); writer.WriteAttributeString("version","1.0"); writer.WriteStartElement("xsl:output"); writer.WriteAttributeString("method","html"); writer.WriteEndElement( ); CreateRootTemplate(writer); CreateInventoryTemplate(writer); CreateDateTemplate(writer); CreateItemsTemplate(writer); CreateItemTemplate(writer); writer.WriteEndElement( ); // xsl:stylesheet writer.WriteEndDocument( ); } private static void CreateRootTemplate(XmlWriter writer) { writer.WriteStartElement("xsl:template"); writer.WriteAttributeString("match","/"); writer.WriteStartElement("html"); writer.WriteStartElement("head"); writer.WriteStartElement("title"); ...

Get .NET & XML now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.