如何在LINQ中返回firstchild值

时间:2012-04-20 09:42:03

标签: c# xml vb.net linq

使用LINQ,我如何只获取以下XML的author元素值:

<?xml version="1.0" encoding="utf-8"?>
<quotes>
  <category name="Sport">
    <author>James Small
      <quote>Quote One</quote>
      <quote>Quote Two</quote>
    </author>
  </category>
  <category name="Music">
     <author>
      Stephen Swann
     <quote />
    </author>
  </category>
</quotes>

我是LINQ的新手,但我已经尝试了

   Dim quotesXMLList As IEnumerable(Of XElement) = From n In q.Descendants("category") _
                                                   Select n
    For Each n In quotesXMLList

        authorList.Add(n.Value)
    Next

但是n.value返回作者和所有子元素值。

3 个答案:

答案 0 :(得分:1)

此查询返回所有作者姓名:

var authorNames =
    from category in q.Elements("category")
    from author in category.Elements("author")
    from textNode in author.Nodes().OfType<XText>()
    select textNode.Value;

答案 1 :(得分:1)

这将安全地检索第一个孩子:

list.Where(x => x.Children.Any()).Select(x => x.Children.First());

答案 2 :(得分:1)

您可以通过更改XML来改善生活:

<?xml version="1.0" encoding="utf-8"?>
<quotes>
  <category name="Sport">
    <author>
      <name>James</name>
      <quote>Quote One</quote>
      <quote>Quote Two</quote>
    </author>
  </category>
  <category name="Music">
     <author>
      <name>Stephen</name>
     <quote />
    </author>
  </category>
</quotes>

然后您可以使用以下名称获取姓名:

var nodes = 
from item in xdoc.Descendants("name")
select new {author = item.Value};