0

LINQを使用して、次のXMLの作成者要素の値のみを取得するにはどうすればよいですか。

<?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は、作成者とすべての子要素の値を返します。

4

3 に答える 3

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};
于 2012-04-20T10:03:00.433 に答える
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;
于 2012-04-20T09:50:28.207 に答える
1

これにより、最初の子が安全に取得されます。

list.Where(x => x.Children.Any()).Select(x => x.Children.First());
于 2012-04-20T09:51:42.433 に答える