Read xml node attribute

后端 未结 1 1529
遇见更好的自我
遇见更好的自我 2021-01-13 10:19

I have an xml document that have nodes like this, What I want to do is get all id\'s attribute value for each ITEM node

相关标签:
1条回答
  • 2021-01-13 11:06

    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.

    0 讨论(0)
提交回复
热议问题