Associating a Stylesheet with an XML Document

Although it’s not part of the actual XSLT specification, there is a way to associate a stylesheet with an XML document. The XML Stylesheet recommendation, Version 1.0, suggests that the xml-stylesheet processing instruction be used to link an XML document to its stylesheets:

<?xml-stylesheet href="stylesheet.xsl" type="text/xsl"?>

Although you’re free to use the xml-stylesheet processing instruction in your source XML document, there is no guarantee that any given XSLT processor will do anything special with it; .NET’s XslTransform, for example, does not.

You can make use of the xml-stylesheet processing instruction even though XslTransform does not use it automatically. Let’s construct a program that examines the source document for an xml-stylesheet processing instruction, and transforms it according to the href contained within it. I’ll just call it Transform.cs.

These familiar lines create an instance of XmlDocument and load it from the first command-line argument:

public class Transform {
  public static void Main(string [ ] args) {

    string source = args[0];
    string destination = args[1];

    XmlDocument document = new XmlDocument( );

The next line will search the loaded XmlDocument for the XPath expression //processing-instruction('xml-stylesheet'). As you will recall, this expression will match any processing instruction with the target xml-stylesheet. If none is found, SelectSingleNode( ) will return a null instance: ...

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.