Tom92
Tom92

Reputation: 31

Reading a XML File using XPath Expression in C#

I am currently having a problem with reading a XML file using XPath expression. I have used the XmlDocument class. When I try reading a particular node from the XML, I get an empty list. The node which I am trying to read is the ID below ProductionRequest.

Here is the XML file which I tried to read:

<?xml version="1.0" encoding="iso-8859-1"?>
<ProductionSchedule xmlns="http://www.wbf.org/xml/b2mml-v02"> 
  <ID>00000020000000</ID>
  <Location>
   <EquipmentID>8283</EquipmentID>
   <EquipmentElementLevel>Site</EquipmentElementLevel>
  <Location>
   <EquipmentID>0</EquipmentID>
   <EquipmentElementLevel>Area</EquipmentElementLevel>
   </Location>
  </Location>
 <ProductionRequest>
    <ID>0009300000000</ID>
    <ProductProductionRuleID>W001</ProductProductionRuleID>
    <StartTime>2017-04-20T23:57:20</StartTime>
    <EndTime>2017-04-20T24:00:00</EndTime>
    </ProductionRequest>
  </ProductionSchedule>

This is the code which I used to read the above XML

using System;
using System.Xml.Linq;
using System.Xml;
using System.Xml.XPath;

namespace XML
{
  class Program
  {
    static void Main(string[] args)
    {
     Console.WriteLine("Hello World!");
     string fullName = "F:\\Programming\\XML\\Example XML.xml";
     XmlDocument xreader = new XmlDocument();

     xreader.Load(fullName);
     XmlNode root = xreader.DocumentElement;
     XmlNodeList xnList1 = 
            xreader.SelectNodes("/ProductionSchedule/ProductionRequest/ID");


    }
  }
 }

I could not find the cause for this problem. Could anyone help me in this regard. Looking forward for valuable inputs.

Upvotes: 2

Views: 3574

Answers (1)

er-sho
er-sho

Reputation: 9771

Your xml contains namespace http://www.wbf.org/xml/b2mml-v02 at root level node <ProductionSchedule>

And you are using the XPath expression /ProductionSchedule/ProductionRequest/ID but this XPath expression is not suitable for this xml document and that's why you can't get any desired value.

You need to use the below XPath expression to get the id's of all <ProductionRequest> node.

XmlNodeList xnList1 = xreader.SelectNodes("//*[name()='ProductionSchedule']/*[name()='ProductionRequest']/*[name()='ID']");

OR you can add namespace manually like

XmlNamespaceManager nsmgr = new XmlNamespaceManager(xreader.NameTable);
nsmgr.AddNamespace("x", "http://www.wbf.org/xml/b2mml-v02");
XmlNodeList xnList1 = xreader.SelectNodes("//x:ProductionSchedule/x:ProductionRequest/x:ID", nsmgr);

And finally, you can read id from any of the parent nodes in variable xnList1 like

foreach (XmlNode id in xnList1)
{
    Console.WriteLine(id.InnerText);
}

Output:

enter image description here

Upvotes: 2

Related Questions