tags:

views:

78

answers:

2

I've got following xml structure:

<artists>
    <artist> 
        <name></name> 
        <image size="small"></image> 
        <image size="big"></image> 
    </artist>
</artists>

I need to select name and image with given attribute (size = big).

var q = from c in feed.Descendants("artist")
            select new { name = c.Element("name").Value, imgUrl = c.Element("image").Value };

how can i specify needed image attribute(size=big) in query above?

+2  A: 

I don't think it is a good idea to have two nodes with the same name, contained within the same nodeset.

It might validate, but I think it would be (better?) simpler to have two distinct nodes like so:

...

<smallImage></smallImage>

<largeImage></largeImage>

...

The best I can think of is to modify the xml using xsl, or...

EDIT - DANGER! UGLY HACK - DANGER!

You could modify the node names using a loop. I bet there is a much more elegant way to do this using Linq-to-xml - but I couldn't quite manage it:

foreach(XElement xe in feed.Descendants("artist").Elements())
            {
                if(xe.Name.LocalName.Equals("image") && xe.Attribute("size").Value.Equals("small"))
                {
                    xe.Name="smallImage";
                    xe.Attributes("size").Remove();
                }

                if (xe.Name.LocalName.Equals("image") && xe.Attribute("size").Value.Equals("big"))
                {
                    xe.Name = "bigImage";
                    xe.Attributes("size").Remove();
                }
            }
adrianos
i dont like two node with same name too, but that's what api response is and i can't change it :(
Denis
+2  A: 

It's quite simple when you know how!

var artistsAndImage = from a in feed.Descendants("artist")
                      from img in a.Elements("image")
                      where img.Attribute("size").Value == "big"
                      select new { Name = a.Element("Name").Value
                                 , Image = img.Value};

This will return all the names and big images for all the artists.

Matt Ellen
that's really simple :) thanx, works just great!
Denis