用linq选择子元素

时间:2010-11-17 22:46:35

标签: c# linq linq-to-xml

您好几天前刚刚参加过LINQ-XML,想知道我做错了什么,或者是不可能做到这一点。我已经四处寻找并且没有任何与我有关的问题,而且我现在已经捣乱了一下。

XML:

<catalog>
<product description="Cardigan Sweater" product_image="cardigan.jpg">
<catalog_item gender="Men's">
  <item_number>QWZ5671</item_number>
  <price>39.95</price>
  <size description="Medium">
    <color_swatch image="red_cardigan.jpg">Red</color_swatch>
    <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
  </size>
  <size description="Large">
    <color_swatch image="red_cardigan.jpg">Red</color_swatch>
    <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
  </size>
</catalog_item>
<catalog_item gender="Women's">
  <item_number>RRX9856</item_number>
  <price>42.50</price>
  <size description="Small">
    <color_swatch image="red_cardigan.jpg">Red</color_swatch>
    <color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
    <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
  </size>
  <size description="Medium">
    <color_swatch image="red_cardigan.jpg">Red</color_swatch>
    <color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
    <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
    <color_swatch image="black_cardigan.jpg">Black</color_swatch>
  </size>
  <size description="Large">
    <color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
    <color_swatch image="black_cardigan.jpg">Black</color_swatch>
  </size>
  <size description="Extra Large">
    <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
    <color_swatch image="black_cardigan.jpg">Black</color_swatch>
  </size>
</catalog_item>

和查询:

        var query =
        from size in
            (
                from catalogItem in cardigan.Descendants("catalog_item")
                where catalogItem.Attribute("gender").Value == "Men's"
                select catalogItem.Descendants("size")
            )
        select size.Elements("color_swatch");

这基本上让我得到了男士们的所有color_swatch,但我一直试图看看我是否可以获得男士大号的所有color_swatch。

提前致谢。

2 个答案:

答案 0 :(得分:0)

只需将您的查询更改为

即可
    var query =
    from size in
        (
            from catalogItem in cardigan.Descendants("catalog_item")
            where catalogItem.Attribute("gender").Value == "Men's"
            select catalogItem.Descendants("size")
        )
    where size.Attribute("description") == "Large"
    select size.Elements("color_swatch");

这样可行,因为您首先获得适用于男性的所有“尺寸”项目,然后从该列表中过滤那些仅抓取“大”的项目。

答案 1 :(得分:0)

好的,所以我又捣乱了一些......我得到了它......

var query =        
from catalogItem in cardigan.Descendants("catalog_item")
where catalogItem.Attribute("gender").Value == "Men's"
from size in catalogItem.Descendants("size")
where size.Attribute("description").Value == "Large"
select size.Elements("color_swatch");

花了大约8个小时,但我明白了!

我去了,基本上得到了几个复杂的xml样本。我想这就是你学习的方式。 :)

谢谢你们:)