I've tried to find a solution for my problem, but my knowledge in this area (Linq, XML) is rather limited. :( 've found a simular construction, but I need a litte bit more complex way of sorting.
Consider the Following XML document:
<Envelope>
<Body>
<Table>
<Trans>
<B>1</B>
<A>3</A>
<C>5</C>
</Trans>
<Trans>
<D>1</D>
<A>6</A>
<C>3</C>
</Trans>
<Trans>
<A>1</A>
<C>3</C>
<B>5</B>
</Trans>
</Table>
</Body>
<Envelope>
Is there any way I can sort the elements inside <Trans> using C#/Linq, or do I have to break up all <Trans> elements and sort them one by one?
Update I have a file and this is what I'm tring to accomplish. ;)
<Envelope>
<Body>
<Table>
<Trans>
<A>3</A>
<B>1</B>
<C>5</C>
</Trans>
<Trans>
<A>6</A>
<C>3</C>
<D>1</D>
</Trans>
<Trans>
<A>1</A>
<B>5</B>
<C>3</C>
</Trans>
</Table>
</Body>
<Envelope>
It really depends on what exactly you want to do (process them in order, or reorder the XML?) and on what exactly you mean "sort" (sort by tag name? sort by value?).
If you just want to process them in order, this is how you can sort all elements inside each <Trans> by value (<D>1</D> before <A>6</A>):
XDocument doc = /* load up your XML */
var sorted = from trans in doc.Descendants("Trans")
select trans.Children().OrderBy(c => int.Parse(c.Value)).ToArray();
Alternatively, here's how to order by tag name (<A>6</A> before <D>1</D>):
var sorted = from trans in doc.Descendants("Trans")
select trans.Children().OrderBy(c => c.Name.LocalName).ToArray();
With the above, sorted will be an enumerable collection of arrays. Each array in the collection represents a <Trans>, and each such array holds the children of the <Trans> in order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With