Tuesday, September 6, 2016

Read or parse XML using XPathDocument

Good day!

In this example, I will show you how to read an XML file using XPathNavigator and XPathDocument classes in .NET. When using these classes, make sure to include the System.Xml and System.Xml.XPath namespaces in your file.
XML File
<?xml version="1.0" encoding="utf-8" ?>
<Invoice  xmlns:inv="http://salesorgchart.abcdefg.com">
  <inv:Customers>
    <inv:TotalSales>134.49</inv:TotalSales>
    -<inv:Customer>
      <inv:Date>2013-11-15</inv:Date>
      <inv:Number>10001</inv:Number>
      <inv:CustomerName>Cherry Pie</inv:CustomerName>
      <inv:PONumber>30002</inv:PONumber>
      <inv:Address>Cebu City Philippines</inv:Address>
      -<inv:Products>
        -<inv:Product>
          <inv:Code>AE445</inv:Code>
          <inv:Category>Liquid Milk</inv:Category>
          <inv:Name>Devondale</inv:Name>
          <inv:Quantity>$100.49</inv:Quantity>
        </inv:Product>
        <inv:Product>
          <inv:Code>AE443</inv:Code>
          <inv:Category>Junk Foods</inv:Category>
          <inv:Name>Pringles</inv:Name>
          <inv:Quantity>$34.00</inv:Quantity>
        </inv:Product>
      </inv:Products>
    </inv:Customer>
  </inv:Customers>
</Invoice>

C# Code
private void ReadXML()
{
 XPathDocument xPath;
 XPathNavigator nav;
 XmlNamespaceManager manager;

 using (StreamReader reader = new StreamReader(xmlPath, UTF8Encoding.Default))
 {
  xPath = new XPathDocument(reader);            
 }

 nav = default(XPathNavigator);
 nav = xPath.CreateNavigator();
 manager = new XmlNamespaceManager(nav.NameTable);
 manager.AddNamespace("inv", "http://salesorgchart.abcdefg.com");
 XPathNodeIterator nodes = nav.Select("//inv:Customers/inv:Customer", manager);

 if (nodes.MoveNext())
 {
  foreach (XPathNavigator child in nodes.Current.SelectChildren(XPathNodeType.All))
  {
   if (child.Name == "inv:Number" || child.Name == "inv:CustomerName")
   {
    Console.WriteLine("{0}: {1}", child.Name, child.Value);
   }
   else
   {
    if (child.HasChildren && child.Name == "inv:Products")
    {
     Console.WriteLine("==============================================");
    
     Console.WriteLine("Products" + "\n");
     foreach (XPathNavigator item in child.SelectChildren(XPathNodeType.All))
     {
      if (item.HasChildren)
      {                                    
       foreach (XPathNavigator product in item.SelectChildren(XPathNodeType.All))
       {
        if (!product.Name.Equals(string.Empty))
        {
         Console.WriteLine("{0}: {1}", product.Name, product.Value);
        }
       }

       Console.Write(Environment.NewLine);
      }                                
     }                                
    }                                                    
   }
  }
 }
}

0 comments:

Post a Comment