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
Attributeobject with a value. You should useAttribute("x").Valueto retrieve it’s value.Try this corrected code:
[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.