Select element with given attribute using linq to xml

前端 未结 2 1718
萌比男神i
萌比男神i 2020-12-11 07:06

I\'ve got following XML structure:


     
         
                  


        
相关标签:
2条回答
  • 2020-12-11 07:45

    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 讨论(0)
  • 2020-12-11 07:57

    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.

    0 讨论(0)
提交回复
热议问题