amity2 amity2 - 8 days ago 5
C# Question

Sorting xelement with different tags in C# based on value

I have the below XML which needs to be sorted based on the value

sequence
tag, the XML for sorting is placed in Totals root node, is this possible in C#. If sequence is empty or is repeating, then leave that tag in its place.

<Totals sequence="001" label="Totals" tooltip="Totals">
<ReturnTotalGrossReceipts sequence="001" datatype="Money" label="Total Receipts" />
<ReturnTotalAdjusts sequence="002" datatype="Money" label="Total Adjustments" />
<ReturnTotalTaxableSales sequence="003" datatype="Money" label="Total Taxable Sales" />
<ReturnTotalTax sequence="005" datatype="Money" label="Total Amount of Tax" />
<ReturnTimelyPay sequence="004" datatype="Money" label="Total Pay" />
<ReturnTotalSalesTaxDue sequence="006" datatype="Money" label="Total Due" />
<ReturnInterest sequence="006" datatype="Money" label="Interest" />
</Totals>

Answer

Following code should give you a sorted list, leaving elements in place if the sequence element is null.

var sXml = "<Totals sequence=\"001\" label=\"Totals\" tooltip=\"Totals\"><ReturnTotalGrossReceipts sequence=\"001\" datatype=\"Money\" label=\"Total Receipts\" /><ReturnTotalAdjusts sequence=\"002\" datatype=\"Money\" label=\"Total Adjustments\" /><ReturnTotalTaxableSales sequence=\"003\" datatype=\"Money\" label=\"Total Taxable Sales\" /><ReturnTotalTax sequence=\"005\" datatype=\"Money\" label=\"Total Amount of Tax\" /><ReturnTimelyPay sequence=\"004\" datatype=\"Money\" label=\"Total Pay\"  /><ReturnTotalSalesTaxDue sequence=\"006\" datatype=\"Money\" label=\"Total Due\"  /><ReturnInterest sequence=\"006\" datatype=\"Money\" label=\"Interest\" /></Totals>";
var xml = XElement.Parse(sXml);
xml
    .Descendants()
    .Select((x, i) => new { Index = i, Element = x })
    .OrderBy(x => Convert.ToInt32(x.Element.Attribute("sequence")?.Value ?? x.Index.ToString()))
    .Select(x => x.Element);