开发者

Select element with given attribute using linq to xml

开发者 https://www.devze.com 2023-01-18 23:34 出处:网络
I\'ve got following XML structure: <artists> <artist> <name></name> <image size=\"small\"></image>

I've got following XML structure:

<artists>
    <artist> 
        <name></name> 
        <image size="small"></image> 
        <image size="big"></image> 
    </ar开发者_高级运维tist>
</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?


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.


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();
                }
            }
0

精彩评论

暂无评论...
验证码 换一张
取 消