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" eg
<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.
That may happen if a node lacks the attribute. Try:
var bar = doc.Descendants("node")
.Where(x => (string)x.Attribute("type") == "type1")
.ToList();
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.
var bar = doc.Descendants() //Checking all the nodes, not just the "node"
.Where(x => x.Attribute("type")?.Value == "type1")//if the attribute "type" is not null, check the Value == "type1",
.ToList();//immediately executes the query and returns a List<XElement> by the value of attribute "type"
this is an option, if you need to check the value of a specific attribute in all nodes of a document / element.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.