Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read xml node attribute

I have an xml document that have nodes like this, <ITEM id="1" name="bleh"... /> What I want to do is get all id's attribute value for each ITEM node that exists in the document.

So, how can I do that?

Edit: I've tried this way and it didn't works:

XmlDocument Doc = new XmlDocument();
        Doc.Load("example.xml");
        XmlNodeList nodeList = Doc.SelectNodes("/ITEM");
        foreach (XmlNode node in nodeList)
        {
            string id = node.Attributes["id"].Value;
            Console.WriteLine(id);
        }
like image 318
Derezzed Avatar asked Sep 15 '13 23:09

Derezzed


1 Answers

You should use XmlNamespaceManager in your call to SelectSingleNode() since your XML does contain a namespace on it:

var doc = new XmlDocument();
doc.Load("example.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("anyname", "http://tempuri.org/zitem.xsd");
foreach (XmlNode node in doc.SelectNodes("//anyname:ITEM", ns))
{
    Console.WriteLine(node.Attributes["id"].Value);
}

That's why you get no result.

The difference from my code to yours is that I am using // so instead of starting at the root of a document, a double forward slash // indicates to an XPath evaluator to look anywhere in an XML document.

Here is my example.xml as sample:

<root>
  <items>
    <ITEM id="1" name="bleh=" />
    <ITEM id="2" name="bleh=" />
    <ITEM id="3" name="bleh=" />
    <ITEM id="4" name="bleh=" />
    <ITEM id="5" name="bleh=" />
    <ITEM id="6" name="bleh=" />
    <ITEM id="7" name="bleh=" />
    <ITEM id="8" name="bleh=" />
  </items>
</root>

And here is how I am reading it:

var doc = new XmlDocument();
doc.Load("example.xml");
foreach (XmlNode node in doc.SelectNodes("//ITEM[@id]"))
{
    Console.WriteLine(node.Attributes["id"].Value);
}

With single slash, the above XPath would look like this:

/root/items/ITEM

I am also using [@id] to ensure that the ITEM element have an ID attribute but that is not necessary if you know they all have an ID attribute.

like image 68
Prix Avatar answered Sep 21 '22 06:09

Prix