需要嵌套的LINQ to XML查询帮助

时间:2010-08-24 00:49:15

标签: c# xml linq

我有一个XML文件如下:

<?xml version="1.0" encoding="utf-8" ?>

<publisher>
<name>abc</name>
<link>http://</link>
<description>xyz</description>

<category title="Top">
<item>
<title>abc</title>
<link>http://</link>
<pubDate>1</pubDate>
<description>abc</description>
</item>

<item>
<title>abc</title>
<link>http://</link>
<pubDate>2</pubDate>
<description>abc</description>
</item>


</category>

<category title="Top2">
<item>
<title>abc</title>
<link>http://</link>
<pubDate>1</pubDate>
<description>abc</description>
</item>

<item>
<title>abc</title>
<link>http://</link>
<pubDate>2</pubDate>
<description>abc</description>
</item>
</category>

</publisher>

我需要在C#中编写一个LINQ to XML查询,它根据提供的属性值返回“category”标记下的所有内容。我尝试了以下代码,但它给了我错误。任何帮助将不胜感激:

        System.Xml.Linq.XElement xml = System.Xml.Linq.XElement.Parse(e.Result);

        IEnumerable<string> items = from category in xml.Elements("category")
                    where category.Attribute("title").Value == "Top"
                    select category.ToString();

1 个答案:

答案 0 :(得分:1)

   IEnumerable<string> items = from category in xml.Descendants("category") 
    where category.Attribute("title").Value == "Top" 
    select category.ToString();

当然,这会给你一个包含一个字符串的列表。如果你只想要其中的字符串:

var items = (from category in xml.Descendants("category") 
            where category.Attribute("title").Value == "Top" 
            select category.ToString()).First(); 

但是,如果你想继续处理XML,你可能真的希望它作为XElement对象:

var items = (from category in xml.Descendants("category") 
            where category.Attribute("title").Value == "Top" 
            select category).First();