<row>
<id>9578</id>
<processes>
<process ID="PROCESS A">
<subprocess ID ="STEP A">
<val>abcde</val>
</subprocess>
</process>
<process ID="PROCESS B">
<subprocess ID ="STEP B">
<val>fghij</val>
</subprocess>
</process>
<process ID="PROCESS C">
<subprocess ID ="STEP C">
<val>klmno</val>
</subprocess>
</process>
</processes>
<row>
I am trying to get the data in the val element, but am having trouble. So far, this is what I have:
XmlNodeReader nodereader = new XmlNodeReader(Xdoc);
nodereader.MoveToContent();
var xdoc = XDocument.Load(nodereader);
var doc_list = xdoc.Descendants("row").Select(x => new
{
id = x.Element("id").Value,
ProcessA = x.Element("processes").Elements("process").Single(attr => attr.Attribute("ID").Value == "PROCESS A").Value
}).ToList();
ProcessA
will contain the values of the val element (in this case, abcde
). But I keep getting a NullReferenceException
. I think I'm almost on the right track, but I still need a little help.
EDIT Thank you everyone for your help but I realize my code works. The issue was just a spelling error due to the id. Instead of
id = x.Element("id").Value,
I accidentally did
id = x.Element("Id").Value,
which resulted in the NullReferenceException for the LINQ. My code to get the val element worked. Moral of the story: sometimes the error might not be where you think it is.