返回所有元素和子元素 [英] Return all Elements and Sub-elements
问题描述
是否可以使用一个LINQ查询一次返回所有元素和子元素的值?使用下面的查询,我可以检索第一个元素,但不能检索子元素.
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,
};
XML文件如下所示:
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?
推荐答案
查询的问题是,第一个file
元素似乎与子file
元素的类型不同.
The problem with your query is that your first file
element seems to be a different type from your child file
elements.
因此,当您实际执行查询时,将找不到子file
元素的name
属性,并且将获得null reference exception when you try to invoke the
Value property of the child
file`元素.
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 the
Valueproperty of the child
file` 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,
};
这篇关于返回所有元素和子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!