2010-11-11 231 views
1

我試圖從XML文檔中獲取元素列表,其中節點具有特定的屬性值。該文件的結構是這樣的:LINQ to 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> 

我想有結果是一個包含具有type =「TYPE1」例如兩個節點的IEnumerable<XElement>

<node type="type1">some text</node> 
    <node type="type1">some more text</node> 

我加載使用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.錯誤。我使用的代碼是

var bar = doc.Descendants("node") 
    .Where(x => x.Attribute("type").Value == "type1") 
    .ToList(); 

任何幫助搞清楚爲什麼我沒有得到結果我希望將不勝感激。

回答

3

如果節點缺少屬性,可能會發生這種情況。嘗試:

var bar = doc.Descendants("node") 
    .Where(x => (string)x.Attribute("type") == "type1") 
    .ToList(); 
+0

好的,這很有效,這個解釋非常有意義。 – Hamman359 2010-11-11 21:44:33

1
var bar = doc.Descendants("node") 
.Where(x => x.Attribute("type") != null && x.Attribute("type").Value == "type1") 
.ToList(); 

添加空值保護解決您的問題。