2012-04-20 43 views
0

返回则firstChild值使用LINQ,我怎么只得到以下XML笔者元素值:如何在LINQ

<?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返回作者和所有子元素值。

回答

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

这将安全地获取第一个孩子:

list.Where(x => x.Children.Any()).Select(x => x.Children.First()); 
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};