[英]How to select a specific node from XDocument having a specific attribute value?
這是我的xml,
<root>
<A>
<B id="ABC">one
</B>
<B id="ZYZ">two
</B>
<B id="QWE">three
</B>
<B>four
</B>
</A>
</root>
使用以下c#代碼僅獲取節點<B id="QWE">three</B>
,
var x = xdoc.Descendants("B").Where(ele => ele.Attribute("id").Value.Equals("QWE"));
但變量x
始終為空,任何幫助表示贊賞!
在您的 xml 示例中,並非所有B
節點都具有id
屬性。 Attribute("id")
將為該節點返回 null,當您訪問Value
on null 時,您會得到NullReferenceException
。
使用下一個代碼來避免該錯誤:
var x = xdoc.Descendants("B")
.Where(ele => (string)ele.Attribute("id") == "QWE");
Attribute
方法返回XElement
。 當您將其轉換為string
,它將采用該元素的字符串表示形式,在我們的示例中,這將是一個屬性的值(您可以在 msdn上查看有關將XElement 轉換為字符串的更多詳細信息)。 現在,當Attribute
返回 null 時,將其轉換為 string 將給出 null。 ==
運算符將始終為 null 和"QWE"
文字返回 false,不會拋出異常。
如果出於某種原因,您不想將XElement
為string
,則可以使用三元運算符查看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.