TechShri from Shriniwas Wani

Custom Search

27 June, 2006

Read XML File ... XPathDocument Approach

private static void ReadXMLxPathApproach()
{
pathForFile = @"D:\Study\Employees.xml";
XPathDocument myXPathDocument = new XPathDocument(pathForFile);

Console.WriteLine("XPathDocument loaded with XML data successfully ...");
Console.WriteLine("Create a Navigator ..."); // Get an XPathNavigator from the XPathDocument

XPathNavigator myXPathNavigator = myXPathDocument.CreateNavigator();
myXPathNavigator.MoveToRoot(); // Initialize the myXPathNavigator to start at the root
DisplayTree(myXPathNavigator); // Display all the nodes

//XmlNodeReader myXmlNodeReader = new XmlNodeReader(myXmlDocument.SelectSingleNode("bookstore/book[3]"));
//FormatXml(myXmlNodeReader);

Console.WriteLine("Using XPathNodeIterator ...");
XPathNodeIterator myXPathNodeIterator = myXPathNavigator.Select("descendant::book/title");
while (myXPathNodeIterator.MoveNext())
{
Console.WriteLine("<" + myXPathNodeIterator.Current.Name + ">" + myXPathNodeIterator.Current.Value);
}


}


// Walks the XPathNavigator tree recursively
public static void DisplayTree (XPathNavigator myXPathNavigator)
{
if (myXPathNavigator.HasChildren)
{
myXPathNavigator.MoveToFirstChild();
Format(myXPathNavigator);
DisplayTree(myXPathNavigator);
myXPathNavigator.MoveToParent();
}
while (myXPathNavigator.MoveToNext())
{
Format(myXPathNavigator);
DisplayTree(myXPathNavigator);
}

}

// Format the output - XPathNavigator Requires namespace using System.Xml.XPath;
private static void Format (XPathNavigator myXPathNavigator)
{
if (!myXPathNavigator.HasChildren)
{
if (myXPathNavigator.NodeType == XPathNodeType.Text)
Console.WriteLine(myXPathNavigator.Value);
else if (myXPathNavigator.Name != String.Empty)
Console.WriteLine("<" + myXPathNavigator.Name + ">");
else
Console.WriteLine();
}
else
{
Console.WriteLine("<" + myXPathNavigator.Name + ">");
// Show the attributes if there are any
if (myXPathNavigator.HasAttributes)
{
if (myXPathNavigator.MoveToFirstAttribute())
{
Console.WriteLine("Attributes of <" + myXPathNavigator.Name + ">");
while (myXPathNavigator.MoveToNextAttribute())
Console.Write("<" + myXPathNavigator.Name + "> " + myXPathNavigator.Value + " ");
// Return to the 'Parent' node of the attributes
myXPathNavigator.MoveToParent();
}
}
}
}

0 Comments:

Post a Comment

<< Home