O'Reilly logo

.NET & XML by Niel M. Bornstein

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 = "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"); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required