使用linq到xml选择具有给定属性的元素

时间:2010-10-07 20:52:52

标签: linq-to-xml

我有以下XML结构:

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

我需要选择具有给定属性的名称和图像(size = big)。

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

如何在上面的查询中指定所需的图像属性(size = big)?

2 个答案:

答案 0 :(得分:8)

当你知道怎么做时,这很简单!

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

这将返回所有艺术家的所有名称和大图。

答案 1 :(得分:1)

我认为在同一节点集中包含两个具有相同名称的节点并不是一个好主意。

它可能会验证,但我认为有两个不同的节点会更好(更好?)更简单:

...

<smallImage></smallImage>

<largeImage></largeImage>

...

我能想到的最好的方法是使用xsl修改xml,或者......

编辑 - 危险! UGLY HACK - 危险!

您可以使用循环修改节点名称。我打赌使用Linq-to-xml有一个很多更优雅的方法 - 但是我无法完全管理它:

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();
                }
            }
相关问题