XPathNavigator in Transformations
The XPathNavigator class provides read-only random access to data and is designed for use as an input to Extensible Stylesheet Language for Transformations (XSLT). It is implemented on the XPathDocument, XmlDataDocument, and XmlDocument. The XPathNavigator is based upon the World Wide Web Consortium (W3C) Data Model as described in section 5 of the XML Path Language (XPath) recommendation.
The XPathNavigator defines a cursor model over any store and provides fast, read-only XPath queries over any data store. The XPathNavigator is also the class to use for iterating over result tree fragments.
The API enables you to get information from the current node in the store and move to connected nodes. The XPathNavigator is a cursor style model that performs traversal over a store using a set of Move methods. The XPathNavigator is always positioned on a node. Any Move method that fails leaves the XPathNavigator unchanged.
The XPathNavigator is the class to use for iterating over result tree fragments. The following code sample creates a result tree fragment within a style sheet by calling the function with the parameter, fragment
, which contains XML.
test.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl ="urn:schemas-microsoft-com:xslt"
xmlns:user="https://www.adventure-works.com"
version="1.0">
<xsl:variable name="fragment">
<authorlist>
<author>Joe</author>
</authorlist>
</xsl:variable>
<msxsl:script language="C#" implements-prefix="user">
<![CDATA[
string NodeFragment(XPathNavigator nav)
{
if (nav.HasChildren)
return nav.Value;
else
return "";
}
]]>
</msxsl:script>
<xsl:template match="/">
<xsl:value-of select="user:NodeFragment($fragment)"/>
</xsl:template>
</xsl:stylesheet>
test.xml
<root>Some text</root>
The following code uses the test.xsl style sheet and test.xml input data.
Imports System
Imports System.IO
Imports System.Xml
Imports System.Xml.Xsl
Imports System.Xml.XPath
Imports System.Text
Public Class sample
Public Shared Sub Main()
Dim xslt As New XslTransform()
xslt.Load("test.xsl")
Dim xd As New XPathDocument("test.xml")
Dim strmTemp = New FileStream("out.xml", FileMode.Create, FileAccess.ReadWrite)
xslt.Transform(xd, Nothing, strmTemp, Nothing)
End Sub 'Main
End Class 'sample
using System;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Text;
public class sample
{
public static void Main()
{
XslTransform xslt = new XslTransform();
xslt.Load("test.xsl");
XPathDocument xd = new XPathDocument("test.xml");
Stream strmTemp = new FileStream("out.xml", FileMode.Create, FileAccess.ReadWrite);
xslt.Transform(xd, null, strmTemp, null);
}
}
Output
The result of the transformation is found in the file out.xml:
<?xml version="1.0" encoding="utf-8"?>Joe