Return all Elements and Sub-elements

梦想的初衷 提交于 2019-12-25 18:58:18

问题


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


来源:https://stackoverflow.com/questions/17218975/return-all-elements-and-sub-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!