返回所有元素和子元素

本文关键字:元素 返回 | 更新日期: 2023-09-27 18:19:19

是否可以使用一个LINQ查询一次返回所有元素和子元素的值?使用下面的查询,我能够检索第一个元素,但不能检索子元素。

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

XML文件看起来像这样:

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

而且,一旦检索到,我如何访问子元素来填充列表框和/或文本框?

返回所有元素和子元素

您查询的问题是您的第一个file元素似乎与您的子file元素类型不同。

因此,当您实际执行查询时,您将无法找到子file元素的name属性,并且您将获得null reference exception when you try to invoke theproperty of the child文件元素。


你似乎想做的事情没有多大意义。但也许你想要这样的东西:

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