LINQ to XML - Trying to select a list of elements

2019-05-30 05:39发布

问题:

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.

回答1:

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

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


回答2:

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.