Return all Elements and Sub-elements

2019-09-21 12:06发布

问题:

Is it possible to use one LINQ query to return the values of all elements and child elements at one time? Using the query below I'm able to retrieve the first element, but not the child elements.

var query = from c in xDoc.Descendants("file")
            orderby c.Name
            select new
            {
                // This gets the main elements
                Name = (string)c.Element("name").Value,
            };

The XML File looks like this:

<files>
    <file id="1">
        <name>A file</name>
        <processDetails>
            <purpose>It's supposed to get files.</purpose>
            <filestoProcess>
                <file>alongfile.pgp</file>
                <file>Anotherfile.pgp</file>
                <file>YetAnotherfile.CSV</file>
            </filestoProcess>
            <schedule>
                <day>Mon</day>
                <day>Tue</day>
                <time>9:00am</time>
            </schedule>
            <history>
                <historyevent>Eh?</historyevent>
                <historyevent>Two</historyevent>
            </history>
        </processDetails>
    </file>
<files>

Also, once retrieved how would I access the child elements to populate a listbox and/or textbox?

回答1:

The problem with your query is that your first file element seems to be a different type from your child file elements.

Because of this, when you actually execute your query, you'll fail to find the name attribute of the child file elements, and you'll get a null reference exception when you try to invoke theValueproperty of the childfile` elements.


What you seem to be trying to do doesn't make very much sense. but maybe you want something like the following:

var query = from c in xdoc.Descendants("file")
            orderby c.Name
            select new
            {
                // This gets the main elements
                Name = c.Element("name") == null ? c.Value : c.Element("name").Value,
            };