user3755946
user3755946

Reputation: 804

XML Reading Issue

I have the following XML doc... I have just left one "line" in for simplicity.

<?xml version="1.0" encoding="UTF-8"?>
<files>
  <file type="INVOICES">
    <document>blah.pdf</document>
    <line>
        <field name="JobNo">321654</field>
        <field name="Issues">1</field>
        <field name="PageCount">200</field>
        <field name="PrintRun">250</field>
        <field name="Size">Small</field>
    </line>
  </file>
</files>

C# code:

static void Main(string[] args)
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load("input.xml");
    XmlNodeList itemNodes = xmlDoc.SelectNodes("//files/file/line");
    foreach (XmlNode itemNode in itemNodes)
    {
         XmlNode jobNo = itemNode.SelectSingleNode("field");

         if (jobNo != null) 
              Console.WriteLine(jobNo.InnerText);
     }
     Console.ReadKey();   
}

This iterates through each line and displays the job number however I want to access the field by it's name JobNo i.e. <field name="JobNo">321654</field> accessed with...

jobNo = itemNode.SelectSingleNode("JobNo");

I know I can change the xml but the XML is supplied by a customer so this is not really an option.

Upvotes: 0

Views: 52

Answers (1)

Volkan Paksoy
Volkan Paksoy

Reputation: 6937

You can access that specific field element by providing the attribute name and value such as

XmlNode jobNo = itemNode.SelectSingleNode("field[@name='JobNo']");

Upvotes: 1

Related Questions