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.
using System; using System.IO; using System.Xml; using System.Xml.Xsl; public class CreateStylesheet { private const string ns = "http://www.w3.org/1999/XSL/Transform"; 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 the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.