简体   繁体   中英

Getting the text in a nested element in XML with C#

<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.

Is this what you want to do?

var doc = XDocument.Parse(@"<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>");

var doc_list = doc
.Elements("row")
.Elements("processes")
.Elements("process")
.Elements("subprocess")
.Select(x => new{
        Id = x.Attribute("ID").Value,
        ProcessVal = x.Element("val").Value
    })

Alternative using XPath instead:

var doc_list = doc
.XPathSelectElements(@"/row/processes/process/subprocess")
.Select(x => new{
    Id = x.Attribute("ID").Value,
    ProcessVal = x.Element("val").Value
})

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM