Problem Writing Linq2Xml Query

Posted by Gavin Draper on Stack Overflow See other posts from Stack Overflow or by Gavin Draper
Published on 2010-04-16T12:58:49Z Indexed on 2010/04/16 13:03 UTC
Read the original article Hit count: 363

Filed under:
|

I'm trying to write a Linq2XML query to query the following XML. I need it to pull back all photos for a given GalleryID.

<Albums>
<Album GalleryId="1" Cover="AlbumCover1.jpg" Title="Album 1">
    <Photos>
        <Photo Title="Image1" URL="img1.jpg" DateAdded="01/01/2010 09:20"/>
        <Photo Title="Image2" URL="img2.jpg" DateAdded="01/01/2010 09:20"/>
        <Photo Title="Image3" URL="img3.jpg" DateAdded="01/01/2010 09:20"/>
    </Photos>
</Album>
<Album GalleryId="2" Cover="AlbumCover1.jpg" Title="Album 2">
    <Photos>
        <Photo Title="Image1" URL="img1.jpg" DateAdded="01/01/2010 09:20"/>
        <Photo Title="Image2" URL="img2.jpg" DateAdded="01/01/2010 09:20"/>

    </Photos>
</Album>
</Albums>

The best I've come up with is

 XDocument xmlDoc = XDocument.Load(GalleryFilePath);
            var x = from c in xmlDoc.Descendants("Album")
                    where c.Attribute("GalleryId").Equals(GalleryId)
                    orderby c.Attribute("Title").Value descending
                    select new
                    {
                        Title = c.Element("Photo").Attribute("Title"),
                        URL = c.Element("Photo").Attribute("URL"),
                        DateAdded = c.Element("Photo").Attribute("DateAdded")
                    };

This returns nothing, I'm guessing this is because I'm telling it to query the Album element then trying to loop through the photo elements. Any tips as to how this should be done?

Thanks

© Stack Overflow or respective owner

Related posts about c#

Related posts about linq-to-xml