LINQ to XML - Trying to select a list of elements

2019-05-30 05:29发布

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>

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>

I'm loading the document using var doc = XDocument.Load(@"C:\document.xml");

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();

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.

2条回答
成全新的幸福
2楼-- · 2019-05-30 06:04
var bar = doc.Descendants("node")
.Where(x => x.Attribute("type") != null && x.Attribute("type").Value == "type1")
.ToList();

Adding a guard for null values solves your problem.

查看更多
祖国的老花朵
3楼-- · 2019-05-30 06:10

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

 var bar = doc.Descendants("node")
    .Where(x => (string)x.Attribute("type") == "type1")
    .ToList();
查看更多
登录 后发表回答