简体   繁体   English

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

[英]Need a Nested LINQ to XML query help

i have a XML file as follows: 我有一个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>

I need to write a LINQ to XML query in C# which returns everything under a "category" tag based on the value of attribute provided. 我需要在C#中编写LINQ to XML查询,该查询根据提供的属性值返回“类别”标签下的所有内容。 I have tried the following code but it gives me error. 我尝试了以下代码,但它给了我错误。 Any help will be appreciated: 任何帮助将不胜感激:

        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();
   IEnumerable<string> items = from category in xml.Descendants("category") 
    where category.Attribute("title").Value == "Top" 
    select category.ToString();

Of course, that's going to give you a list with one string in it. 当然,这将为您提供一个包含一个字符串的列表。 If you want just the string in it: 如果只想在其中输入字符串:

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

But, if you want to continue processing the XML, you probably really want it as a XElement object: 但是,如果您想继续处理XML,则可能真的希望将其作为XElement对象:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM