简体   繁体   中英

How to select a specific node from XDocument having a specific attribute value?

Here is my xml,

<root>
 <A>
    <B  id="ABC">one
    </B>
    <B id="ZYZ">two
    </B>
    <B  id="QWE">three
    </B>
    <B>four
    </B>
  </A>
</root>

using following c# code to fetch only the node <B id="QWE">three</B> ,

var x = xdoc.Descendants("B").Where(ele => ele.Attribute("id").Value.Equals("QWE"));

but variable x is always null, any help appreciated!

In your xml example, not all B nodes have id attribute. Attribute("id") will return null for that nodes and when you access Value on null, you get a NullReferenceException .

Use next code to avoid that error:

var x = xdoc.Descendants("B")
            .Where(ele => (string)ele.Attribute("id") == "QWE");

Attribute method returns XElement . When you cast it to string , it takes the string representation of that element, in our case that would be the value of an attribute (you can see more details on casting XElement to string at msdn ). Now, when Attribute returns null, casting it to string would give a null. == Operator will always return false for null and "QWE" literal, no exception will be thrown.

If, for some reason, you don't want to cast XElement to string , you can use ternary operator to see if id attribute is present for ele node (code becomes less readable quite quickly).

var x = xdoc.Descendants("B")
            .Where(ele => (ele.Attribute("id") != null ? ele.Attribute("id").Value : null) == "QWE");

为什么不是 XPath?

var x = xdoc.XPathSelectElement("//B[@id='QWE']")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM