Read xml node attribute

≡放荡痞女 提交于 2019-12-19 08:12:42

问题


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);
        }

回答1:


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.



来源:https://stackoverflow.com/questions/18818618/read-xml-node-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!