2010-08-24 87 views
0

我有一个XML文件,如下所示:需要一个嵌套的LINQ to 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> 

我需要一个LINQ写在C#中的XML查询了基于价值下一个“类”标签返回的一切提供的属性。我已经尝试了下面的代码,但它给了我错误。任何帮助将不胜感激:

 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(); 
+0

我几乎可以肯定的是选择应来之前。无论如何,请粘贴错误。 – 2010-08-24 00:50:23

+0

“SELECT before WHERE”只有SQL规则,而不是LINQ。错误描述将​​有很大帮助。对于我来说,目前还不清楚为什么在没有“Top”值的标题时搜索“Top”。更多的源代码也可能是成功的。 – Budda 2010-08-24 01:01:19

+0

@Hamish @Budda:谢谢你的回应。这就是查询执行后在“项目”中返回的内容: System.Collections.Generic.IEnumerator .Current ='System.Collections.Generic.IEnumerable '不包含'System'的定义,并且没有扩展方法'系统'接受类型'System.Collections.Generic.IEnumerable '类型的第一个参数可以找到(你是否缺少一个使用directiv ... 我想要的是所有的标签返回取决于例如“Top”,“Top2” – Taimi 2010-08-24 01:07:25

回答

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(); 
+0

感谢James !!上面发布的第三个查询是我正在寻找的内容,它像一个魅力一样工作!谢谢! – Taimi 2010-08-24 01:15:35