rAm rAm - 3 months ago 10
C# Question

Compare XML Node Values using Name Tag and Remove the Tag

I have the XML Example

<order>
<orderItem>
<OrderId>Ex1</OrderId>
<amount>100</amount>
</orderItem>
<orderItem>
<OrderId>Ex2</OrderId>
<amount>150</amount>
</orderItem>
<orderItem>
<OrderId>Ex1</OrderId>
<amount>250</amount>
</orderItem>
</order>


If the OrderId tag value is Equal to another OrderId tag value then add the Amount Tag and remove the newly added tag.

The Result Output i need should be like below

<order>
<orderItem>
<OrderId>Ex1</OrderId>
<amount>350</amount>
</orderItem>
<orderItem>
<OrderId>Ex2</OrderId>
<amount>150</amount>
</orderItem>
</order>


The OrderId value should be Changed.

string filename = "File Location";
var doc = XDocument.Load(filename);
var results = doc.Descendants("order");
var orderItemcount = results.Descendants("orderItem").Count();


I don't know what to do next.

Thanks in Advance.

Answer

There are a few steps:

  1. Group your orders together by id, and then for each grouping...
  2. Get the total amount
  3. Set the first order amount to the total
  4. Remove the remaining orders

The code is fairly straightforward:

var ordersById = doc.Descendants("orderItem")
    .GroupBy(x => (string) x.Element("OrderId")); // 1

foreach (var grouping in ordersById)
{
    var total = grouping
        .Sum(x => (decimal) x.Element("amount")); // 2

    grouping.First().SetElementValue("amount", total); // 3

    grouping.Skip(1).Remove(); // 4
}

See this fiddle for a working demo.