Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

c# - Return all Elements and Sub-elements

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...