2012-04-20 6 views
0

でのfirstChild値を返すにはどうすればよい、どのように私は、次のXMLのためのauthor要素の値を取得します:私はLINQを使用して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}; 
関連する問題