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( );
    document.Load(source);

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 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.