0

I am trying to sort an XML document by element using LINQ. The XML is the following.

<Person>
    <aaaInformation>
        <lastName>Johnson</lastName>
        <firstName>Zion</firstName>
        <birthInfo>
            <town>Los Angeles</town>
            <hospital>LA Hospital</hospital>
        </birthInfo>
    </aaaInformation>
    <Gender>Male</Gender>
</Person>

What I would like it to look like is below. (i.e. aaaInformation and Gender were left in the same position, birthInfo was moved to the top since it comes alphabetically before firstName/lastName, and lastName was moved to the bottom. Town and Hospital are also flipped.

<Person>
    <aaaInformation>
        <birthInfo>
            <hospital>LA Hospital</hospital>
            <town>Los Angeles</town>
        </birthInfo>
        <firstName>Zion</firstName>
        <lastName>Johnson</lastName>
    </aaaInformation>
    <Gender>Male</Gender>
</Person>

Is there an easy way to do this? Additionally, these elements are just a small sample of a larger document with significantly more distinct elements, and thus I will not know ahead of time what the names of these elements are.

kashmoney
  • 412
  • 1
  • 5
  • 17
  • 6
    Possible duplicate of [Change the order of elements when serializing XML](https://stackoverflow.com/questions/6455067/change-the-order-of-elements-when-serializing-xml) – xdtTransform Nov 06 '18 at 14:26
  • 4
    FWIW: what you call *attributes* are actually *elements*. – Dan Wilson Nov 06 '18 at 14:27
  • @xdtTransform that question seems different than what I am trying to do since the poster appears to be trying to hardcode the solution. Additionally, the answer doesn't provide the method used to actually create the output that he/she posts – kashmoney Nov 06 '18 at 14:48
  • 1
    additionally, that poster knows the structure of the document (i.e. he knows every attribute of the class), whereas this portion that I posted is just a very small sample of a larger document with hundreds of elements with distinct names – kashmoney Nov 06 '18 at 14:53
  • Why is it that you need to use linq -- I'd think you want to use the xml features of C# – Hogan Nov 06 '18 at 14:54
  • I don't necessarily need to, I just thought it might be easier – kashmoney Nov 06 '18 at 14:55
  • Another possible duplicate (that actually uses Linq) https://stackoverflow.com/questions/6333241/reorder-xml-nodes – tweray Nov 06 '18 at 15:53
  • Possible duplicate of [Reorder XML nodes](https://stackoverflow.com/questions/6333241/reorder-xml-nodes) – Hogan Nov 06 '18 at 22:01
  • in that example just use x.Name instead of x.Value @kashmoney – Hogan Nov 06 '18 at 22:18

0 Answers0