2010-11-11 131 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(); 

添加空值保护解决您的问题。