Select element with given attribute using linq to xml

寵の児 提交于 2019-12-17 20:14:13

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/3885795/select-element-with-given-attribute-using-linq-to-xml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!