LINQ to XML-尝试通过元素的属性值选择元素列表 [英] LINQ to XML - Trying to select a list of elements by the value of their attributes

查看:62
本文介绍了LINQ to XML-尝试通过元素的属性值选择元素列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从XML文档中获取元素列表,其中节点具有特定的属性值.该文档的结构如下:

I'm trying to get a list of elements out of an XML document where the nodes have a specific attribute value. The document is structured something like this:

<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"的节点.

The result I'd like to have is an IEnumerable<XElement> containing the two node with type="type1" e.g.

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

我正在使用var doc = XDocument.Load(@"C:\document.xml");

我可以从包含要使用的节点的属性中获取IEnumerable<XAttribute>

I can get an IEnumerable<XAttribute> containing the attributes from the nodes I want using

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

但是,如果我尝试使用下面的代码获取包含那些属性的元素,则会出现Object reference not set to an instance of an object.错误.我使用的代码是

However, if I try to get the elements that contain those attributes using the code below I get an Object reference not set to an instance of an object. error. The code I used is

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

在弄清楚为什么我没有得到我期望的结果方面的任何帮助将不胜感激.

Any help on figuring out why I'm not getting the results I expect would be appreciated.

推荐答案

如果节点缺少属性,则可能会发生这种情况.试试:

That may happen if a node lacks the attribute. Try:

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

这篇关于LINQ to XML-尝试通过元素的属性值选择元素列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆