如何使用LINQ to XML从XML响应中单独获取所有子节点值



我的XML响应:

<Items>
<Item>
<ASIN>1212121</ASin>
 <ItemAttributes>
  <Title>aaaa</Title>
  </ItemAttributes>
  <Variations>
   <Item>
    <ItemAttributes>
     <color>Red</color>
     </ItemAttributes>
     </Item>
     Item>
    <ItemAttributes>
     <color>yellow</color>
     </ItemAttributes>
     </Item>
       Item>
    <ItemAttributes>
     <color>pink</color>
     </ItemAttributes>
     </Item>
      </Variations>
    </Item>
  <Item>
   ASIN>1211111</ASin>
 <ItemAttributes>
  <Title>bbb</Title>
  </ItemAttributes>
  <Variations>
   <Item>
    <ItemAttributes>
     <color>Green</color>
     </ItemAttributes>
     </Item>
      </Variations>
  </Item>
  </Items>

在这里,我收到了每页十个项目。我现在所需要的就是,获取每个物品的颜色。我使用了以下代码。

   var Color = xd.Descendants(ns + "Items").Elements(ns+"Item").Elements(ns + "Variations").Elements(ns + "Item").Elements(ns + "ItemAttributes").Elements(ns + "Color").Select(cl => new
        {
            clr = cl.Value
        }).ToList();

此Xml返回所有项的颜色。首先它是红色的。第二个是绿色的。它上升到第十项。现在我上面的LINQ代码为所有项目返回颜色。,它以红色、黄色、粉色、绿色的形式返回。。但我必须单独展示第一个项目的颜色(红色)。

最后,我必须显示项目->项目->变体->项目->项目属性->颜色输出:对于第一项。,红色、黄色、粉红色对于第二项,绿色,。。

试用,

   var Color = xd.Descendants(ns + "Items").Elements(ns + "Item").Select(o => string.Join(",", o.Elements(ns + "Variations")
            .Elements(ns + "Item")
            .Elements(ns + "ItemAttributes")
            .Elements(ns + "Color")
            .Select(x => x.Value).ToArray())).ToList<string>();

仍然不能100%清楚您需要什么,但我怀疑它是这样的:

foreach (var item in xd.Descendants(ns + "Items").Elements(ns + "Item"))
{
    // Do anything you need on a per-item basis here
    Console.WriteLine("Got item: {0}", item.Element("ASIN").Value);
    var colors = item.Elements(ns + "Variations")
                     .Elements(ns + "Item")
                     .Elements(ns + "ItemAttributes")
                     .Elements(ns + "Color")
                     .Select(x => x.Value);
    foreach (var color in colors)
    {
        Console.WriteLine("  Color: {0}", color);
    }
}

最新更新