Introduction to the XPathDocument

Introduction to the XPathDocument

In the previous sections, you received an overview of the basics of XPath. This section shows you how to use XPath in .NET.

As previously described, the .NET framework presents a set of classes for working with XPath. Serving as a gateway into the .NET Framework's XPath world, the XPathDocument class is similar to the XmlDocument class. However, it doesn't build a tree of XML nodes in memory, but rather processes them one node at a time building XML nodes only when you require them. The main purpose of the XPathDocument class is to perform XPath queries and XSL transformations.

Listing 8.7 presents an example that utilizes the XPathDocument and XPathNavigator classes. The following XML snippet is used by Listing 8.7:

 <?xml version="1.0" encoding="utf-8" ?> <companies>         <company name="Siemens">                 <cell-phones>                         <cell-phone name="C35" year="2000">Cell phone C35</cell-phone>                         <cell-phone name="MC60" year="2003">Cell phone MC60</cell-phone>                 </cell-phones>         </company>         <company name="Motorola">                 <cell-phones>                         <cell-phone name="C350" year="2001">Cell phone C350</cell-phone>                         <cell-phone name="T205" year="2000">Cell phone T205</cell-phone>                 </cell-phones>         </company> </companies> 

Listing 8.7. Using XPathDocument and XPathNavigator

[View full width]

 using System; using System.Xml.XPath; namespace XPathSample {         class XPathSample {                 [STAThread]                 static void Main(string[] args) {                   XPathDocument xpathDocument = new XPathDocument("../../sample.xml");                   XPathNavigator xpathNavigator = xpathDocument.CreateNavigator();                   xpathNavigator.MoveToRoot();                   NavigateTree(xpathNavigator, 0);                 }                 private static void NavigateTree (                                       XPathNavigator xpathNavigator, int depth) {                         if (xpathNavigator.HasChildren) {                                 xpathNavigator.MoveToFirstChild();                                 DisplayNode(xpathNavigator, depth);                                 depth ++;                                 NavigateTree(xpathNavigator, depth);                                 depth --;                                 while (xpathNavigator.MoveToNext()) {                                         DisplayNode(xpathNavigator, depth);                                         depth ++;                                         NavigateTree(xpathNavigator, depth);                                         depth --;                                 }                                 xpathNavigator.MoveToParent();                         }                 }                 private static void DisplayNode(                                       XPathNavigator xpathNavigator, int depth) {                         string prefix = new String(' ', depth * 3);                         if (xpathNavigator.NodeType == XPathNodeType.Text) {                           Console.Out.WriteLine(prefix + "Node: " + xpathNavigator.Value + ".  ");                         } else {                           Console.Out.Write(prefix + "Node: <" + xpathNavigator.Name + ">. ");                           if (xpathNavigator.HasAttributes) {                             int attributesCount = 1;                             while (xpathNavigator.MoveToNextAttribute()) {                               attributesCount ++;                             }                             Console.Out.Write("Count of attributes: " + attributesCount +  ".");                             if (attributesCount != 1) {                               xpathNavigator.MoveToParent();                             }                           }                           Console.Out.WriteLine();                         }                 }         } } 

In Listing 8.7, we've created an instance of the XPathDocument class that allows us only to create an instance of the XPathNavigator instance. This class is mostly used for collaboration with XPathDocument. It allows us to navigate through the XML document and perform XPath queries.

After that, we've created an XPathNavigator instance by invocation of the CreateNavigator() method of the XPathDocument class.

The last step is an invocation of the custom method NavigateTree(). This one is recursive and navigates through all nodes (beginning from root) of the XML document.

As soon as we review the use of the XPathNavigator and XPathDocument classes, we can start a discussion of how to perform XPath queries. The following example shows how to execute XPath queries by using XPathNavigator and how to navigate the result set through XPathNodeIterator. Listing 8.8 shows how to search all last cell phones in each node located by path: companies/company/cell-phones.

Listing 8.8. XPathNodeIterator Using Sample
 using System; using System.Xml.XPath; namespace XPathSample {   class XPathNodeIteratorSample   {     [STAThread]     static void Main(string[] args)     {       XPathDocument xpathDocument = new XPathDocument("../../sample.xml");       XPathNavigator xpathNavigator = xpathDocument.CreateNavigator();       XPathNodeIterator xpathNodeIterator =         xpathNavigator.Select("//companies/company/cell-phones/cell-phone[last()]");       int i = 0;       Console.Out.WriteLine("Count of nodes that match to XPath query: " + xpathNodeIterator.Count);       while (xpathNodeIterator.MoveNext())       {         Console.Out.WriteLine((++i) + ". Name: <" +           xpathNodeIterator.Current.Name + ">. Value: " + xpathNodeIterator.Current.Value + ".");       }     }   } } 

Introduction to XSLT

XSLT stands for eXtensible Stylesheet Language: Transformations. It is a language which, according to the very first sentence in the specification (found at, is primarily designed for transforming one XML document into another. However, XSLT is more than capable of transforming XML to HTML and many other text-based formats, so a more general definition might be as follows: XSLT is a language for transforming the structure of an XML document. Now we are going to discuss why we might need to transform XML.

XML is a simple, standard way to interchange structured textual data between computer programs. Part of its success comes because it is also readable and writable by humans using nothing more complicated than a text editor, but this doesn't alter the fact that it is primarily intended for communication between software systems. As such, XML satisfies two compelling requirements:

  • Separating data from presentation

  • Transmitting data between applications

Another of the key benefits of XML is that it unifies the worlds of documents and data, providing a single way of representing structure regardless of whether the information is intended for human or machine consumption. The main point is that whether the XML data is ultimately used by people or by a software application, it will very rarely be used directly in the form it arrives in; it must first be transformed into "something else." To communicate with a human reader, that something else might be a document that can be displayed or printed: for example, an HTML file, a PDF file, or even audible sound. Converting XML to HTML for display is probably the most common application of XSLT today. After you have the data in HTML format, it can be displayed on any browser.

To transfer data between different applications, you need to be able to transform data from the data model used by one application to the model used in another. To load the data into an application, the required format might be a comma-separated-values file, a SQL script, an HTTP message, or a sequence of calls on a particular programming interface. Alternatively, it might be another XML file using a different vocabulary from the original. As XML-based electronic commerce becomes widespread, so the role of XSLT in data conversion between applications also becomes ever more important. Just because everyone is using XML does not mean the need for data conversion will disappear. There will always be multiple standards in use. So, XSLT is an ideal tool for transforming an XML document of one format to an XML document with another format.

Transforming XML Documents

Let's discuss how we can use XSLT in .NET. All XSL instructions are performed by an XSL processor. As input data, the XSL processor requires an XML document that should be formatted and an XSL document. After processing, it could return another XML document (that is based on the input XML), HTML document, or another structured document (for example, PDF).

All classes required for XSL transformations are located in the following namespaces: System.Xml (XmlTextWriter class), System.Xml.Xsl (XslTransform class), and System.Xml.XPath (XPathDocument class).

Before we create an example, we should create the XML file that should be transformed (Listing 8.9) and the XSLT file that contains the transformation template (Listing 8.10).

Listing 8.9. XML File That Should Be Transformed
 <?xml version="1.0" encoding="utf-8" ?> <cell-phones>         <cell-phone name="C35" year="2000" company="Siemens"/>         <cell-phone name="MC60" year="2003" company="Siemens"/>         <cell-phone name="C350" year="2001" company="Motorola"/>         <cell-phone name="T205" year="2000" company="Motorola"/> </cell-phones> 

As you can see, the XML file defines a set of cell phones (cell-phones/cell-phone tag) with the attributes name, year, and company.

Listing 8.10. XSL File That Contains Transformation Template
 <xsl:stylesheet xmlns:xsl="" version="1.0"> <xsl:output method="html" />  <xsl:template match="/">    <html>      <body>        <table width="100%">           <tr>             <td width="30%"><b>Cell Phone's Name</b></td>             <td width="30%"><b>Company</b></td>             <td width="40%"><b>Creation Date</b></td>           </tr>           <tr>             <td colspan="3">               <hr width="100%"/>             </td>           </tr>           <xsl:for-each select="/cell-phones/cell-phone">             <tr>                <td width="30%"><xsl:value-of select="@name"/></td>                <td width="30%"><xsl:value-of select="@company"/></td>                <td width="40%"><xsl:value-of select="@year"/></td>             </tr>           </xsl:for-each>        </table>      </body>    </html>  </xsl:template> </xsl:stylesheet> 

In looking at the XML file in Listing 8.10, you will see a tag containing the following element: <xsl:stylesheet>. This is a mandatory element in every XSL stylesheet. The second tag (<xsl:output>) indicates the output type and the next tag (<xsl:template>) is used to define the processing of the sample.xml file.

From there, the example uses a simple XPath selection query to get the data and insert it in into HTML tags.


You should understand that this chapter doesn't cover the syntax of XSL technology and doesn't explain the structure of stylesheets and rules of XSL documents creation. For more information on the structure and syntax of stylesheets, visit the website.

Listing 8.11 presents a simple example that performs XSL transformations.

Listing 8.11. XSL Transformation Sample Source Code
 using System; using System.Xml; using System.Xml.Xsl; using System.Xml.XPath; namespace XSLTSample {   class XSLTSample   {     [STAThread]     static void Main(string[] args)     {       XslTransform xslTransform = new XslTransform();       XPathDocument xpathDocument = new XPathDocument("../../sample.xml");       XmlTextWriter xmlTextWriter = new XmlTextWriter("../../sample.html", null);       xslTransform.Load("../../sample.xslt");       xslTransform.Transform(xpathDocument, null, xmlTextWriter);     }   } } 

Let's discuss it step by step:

  • First, we created an instance of the XslTransform class (System.Xml.Xsl namespace).

  • Following that we created XPathDocument and initialized it with our XML document (sample.xml). XPathDocument will be used during the transformation process as source for the TRansform() method.

  • The next step is instantiation of the XmlTextWriter class. We've initialized it with the filename of the location where resulting HTML should be written (sample.html).

  • In the next step, we initialized an instance of the XslTransform class with the file that contains the XSLT template (sample.xslt).

  • Finally, we invoked the transform() method of XslTransform class and passed to it the XPathDocument class's instance and the XmlTextWriter class's instance that were created earlier.

After the example has been executed, we can view the HTML file generated as a result of the transformation (see Figure 8.1).

Figure 8.1. The generated HTML file.

    Visual C#. NET 2003 Unleashed
    Visual C#. NET 2003 Unleashed
    ISBN: 672326760
    EAN: N/A
    Year: 2003
    Pages: 316 © 2008-2017.
    If you may any questions please contact us: