[英]LINQ to XML - Trying to select a list of elements by the value of their attributes
我正在嘗試從節點具有特定屬性值的 XML 文檔中獲取元素列表。 該文檔的結構如下:
<root>
<node type="type1">some text</node>
<node type="type2">some other text</node>
<node type="type1">some more text</node>
<node type="type2">even more text</node>
</root>
我想要的結果是一個IEnumerable<XElement>
包含 type="type1" 的兩個節點,例如
<node type="type1">some text</node>
<node type="type1">some more text</node>
我正在使用var doc = XDocument.Load(@"C:\\document.xml");
加載文檔var doc = XDocument.Load(@"C:\\document.xml");
我可以獲得一個IEnumerable<XAttribute>
包含我想要使用的節點的屬性
var foo = doc.Descendants("node")
.Attributes("type")
.Where(x => x.Value == "type1")
.ToList();
但是,如果我嘗試使用下面的代碼獲取包含這些屬性的元素,則會得到一個Object reference not set to an instance of an object.
的Object reference not set to an instance of an object.
錯誤。 我使用的代碼是
var bar = doc.Descendants("node")
.Where(x => x.Attribute("type").Value == "type1")
.ToList();
任何幫助弄清楚為什么我沒有得到我期望的結果將不勝感激。
如果節點缺少該屬性,則可能會發生這種情況。 嘗試:
var bar = doc.Descendants("node")
.Where(x => (string)x.Attribute("type") == "type1")
.ToList();
var bar = doc.Descendants("node")
.Where(x => x.Attribute("type") != null && x.Attribute("type").Value == "type1")
.ToList();
為空值添加保護可以解決您的問題。
var bar = doc.Descendants() //Checking all the nodes, not just the "node"
.Where(x => x.Attribute("type")?.Value == "type1")//if the attribute "type" is not null, check the Value == "type1",
.ToList();//immediately executes the query and returns a List<XElement> by the value of attribute "type"
這是一個選項,如果您需要檢查文檔/元素的所有節點中特定屬性的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.