.NET FAQs Unleashed!
 
    
    

How to read XML documents using the XPathDocument class?

The XPathDocument class is based on a DOM parsing approach. The data is read directly from the DOM object of the XML.

 

Say we have the following XML located on your computer at C:\students.xml

 

<Students>

                <Student>

                <Name>Elena</Name>

                <Id>405</Id>

</Student>

                <Student>

                <Name>John</Name>

                <Id>406</Id>

</Student>

</Students>

 

In order to read the XML above using XPathDocument, checkout the following piece of code:

 

using System;

using System.IO;using System.Xml;

using System.Xml.XPath;

 

public partial class Working_With_XPathDocument : System.Web.UI.Page

{

  int i;

  string str;

 

  protected void Page_Load(object sender, EventArgs e)

  {

    string strFile = Path.Combine("C:\", "students.xml");

 

    XPathDocument xmldoc = new XPathDocument(strFile);

    XPathNavigator nav = xmldoc.CreateNavigator();

 

    foreach (XPathNavigator xpnav in nav.Select("students/student"))

    {

    i++;

    str += "<tr class='alt" + (i % 2) + "'>" + "<td>" + xpnav.SelectSingleNode("@name").Value;

    str +=  "</td><td>" + xpnav.SelectSingleNode("Id").Value + "</td></tr>";

    }

    string th = "<th>Name</th><th>Id</th>";

    div1.InnerHtml = "<table cellspacing='0' cellpadding='3'>" + th + tr + "</table>";

  }

}

 

The XPathNavigator is an object used to navigate across the XML Document.

 

If you are aware of the XPath Query Language, you may write programs to directly query XML documents

Silverlight DOM Parser   Parents of Child Elements   XML document using LINQ   XML document using XDocument and XElement?   Attributes and XAttribute    Read XML using XPathDocument    Search XML using LINQ   Serialize and deserialize XML    Empty XML element   Advantage of XmlReader and XmlWriter   Well formed XML VS Valid XML    XHTML VS HTML   Define XML  

More Interview Questions.....