Thirisangu Ramanathan
Thirisangu Ramanathan

Reputation: 614

How can i get all subnode values separately from XML Response using LINQ to XML?

My XML Response:

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

Here, I received ten Item Per Page. All i need now, to Get the color of each Item. I used the following code.

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

This Xml Return the color of all Item. In first it is red. In second it is green. It goes upto item ten. Now my above LINQ code return color for all Item., It return as Red,yellow.pink,green.. But I have to show the color of first item (Red) separately.

Finally, i have to show items->Item->Variations->Item->ItemAttributes->color Output: For First Item., Red,Yellow,Pink For second item , Green,..

Upvotes: 0

Views: 154

Answers (2)

Jignesh Thakker
Jignesh Thakker

Reputation: 3698

Try with,

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500805

It's still not 100% clear what you need, but I suspect it's something like this:

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

Upvotes: 1

Related Questions