How to: Transform a Node Fragment

How to: Transform a Node Fragment

When you transform data contained in an XmlDocument or XPathDocument object the XSLT transformations apply to a document as a whole. In other words, if you pass in a node other than the document root node, this does not prevent the transformation process from accessing all nodes in the loaded document. To transform a node fragment, you must create a separate object containing just the node fragment, and pass that object to the Transform method.

To transform a node fragment

  1. Create an object containing the source document.

  2. Locate the node fragment you wish to transform.

  3. Create separate object with just the node fragment.

  4. Pass the node fragment to the Transform method.

The following example transforms a node fragment and outputs the results to the console.

// Load an XPathDocument.
XPathDocument doc = new XPathDocument("books.xml");

// Locate the node fragment.
XPathNavigator nav = doc.CreateNavigator();
XPathNavigator myBook = nav.SelectSingleNode("descendant::book[@ISBN = '0-201-63361-2']");

// Create a new object with just the node fragment.
XmlReader reader = myBook.ReadSubtree();

// Load the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform();

// Transform the node fragment.
xslt.Transform(reader, XmlWriter.Create(Console.Out, xslt.OutputSettings));



  <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
  <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
  <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
    <title>The Gorgias</title>


<stylesheet version="1.0" xmlns="" >
   <output method="text" /> 
   <template match="/">
      Book title is <value-of select="//title" /> 


Book title is The Confidence Man.

© 2016 Microsoft