简体   繁体   English

如何从具有特定属性值的 XDocument 中选择特定节点?

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

Here is my xml,这是我的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> ,使用以下c#代码仅获取节点<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!但变量x始终为空,任何帮助表示赞赏!

In your xml example, not all B nodes have id attribute.在您的 xml 示例中,并非所有B节点都具有id属性。 Attribute("id") will return null for that nodes and when you access Value on null, you get a NullReferenceException . Attribute("id")将为该节点返回 null,当您访问Value on null 时,您会得到NullReferenceException

Use next code to avoid that error:使用下一个代码来避免该错误:

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

Attribute method returns XElement . Attribute方法返回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 ).当您将其转换为string ,它将采用该元素的字符串表示形式,在我们的示例中,这将是一个属性的值(您可以在 msdn上查看有关将XElement 转换为字符串的更多详细信息)。 Now, when Attribute returns null, casting it to string would give a null.现在,当Attribute返回 null 时,将其转换为 string 将给出 null。 == Operator will always return false for null and "QWE" literal, no exception will be thrown. ==运算符将始终为 null 和"QWE"文字返回 false,不会抛出异常。

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).如果出于某种原因,您不想将XElementstring ,则可以使用三元运算符查看ele节点是否存在id属性(代码很快变得不那么可读)。

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']")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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