繁体   English   中英

如何使用LINQ to XML将所有子节点值与XML Response分开?

[英]How can i get all subnode values separately from XML Response using LINQ to 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>

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

   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返回所有Item的颜色。 首先它是红色的。 第二,它是绿色的。 它上升到第十项。 现在我上面的LINQ代码返回所有Item的颜色。它返回为Red,yellow.pink,green ..但是我必须分别显示第一项(Red)的颜色。

最后,我必须显示items-> Item-> Variations-> Item-> ItemAttributes-> color Output:For First Item。,Red,Yellow,Pink For second item,Green,..

它仍然不是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);
    }
}

试试,

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM