tags:

views:

33

answers:

1

i have a XML file as follows:

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

<publisher>
<name>abc</name>
<link>http://&lt;/link&gt;
<description>xyz</description>

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

<item>
<title>abc</title>
<link>http://&lt;/link&gt;
<pubDate>2</pubDate>
<description>abc</description>
</item>


</category>

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

<item>
<title>abc</title>
<link>http://&lt;/link&gt;
<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. 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();
+1  A: 
   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:

var items = (from category in xml.Descendants("category") 
            where category.Attribute("title").Value == "Top" 
            select category).First(); 
James Curran
thanks a bunch James!! the third query which you posted above was what I was looking for. It worked like a charm! thank you!
Taimi