Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
229 views
Welcome To Ask or Share your Answers For Others

1 Answer

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,
            };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...