简体   繁体   中英

Problem Writing Linq2Xml Query

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 int.Parse(c.Attribute("GalleryId").Value) == GalleryId
                    orderby c.Attribute("Title").Value descending
                    select new
                    {
                        Title = c.Element("Photos").Element("Photo").Attribute("Title").Value,
                        URL = c.Element("Photos").Element("Photo").Attribute("URL").Value,
                        DateAdded = c.Element("Photos").Element("Photo").Attribute("DateAdded").Value
                    };

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

Edit : Code updated to reflect answers

It's a common mistake to confuse the Attribute object with a value. You should use Attribute("x").Value to retrieve it's value.

Try this corrected code:

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

[Update] To retrieve a list of photo's, I've set the from to the photo elements, and the where to the album, which is 2 levels up in the provided sample XML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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