Home > Mobile >  how to sort xml nodes
how to sort xml nodes

Time:12-29

I have an XML file in which I want to sort the Object nodes alphabetically and write them back to the file. The raw file looks like this:

<?xml version="1.0" encoding="utf-8"?>
<Package>
  <Objects>
    <Object Type="Package">moB</Object>
    <Object Type="Package">moA</Object>
    <Object Type="Package">moC</Object>
  </Objects>
</Package>

The expected output should be:

<?xml version="1.0" encoding="utf-8"?>
<Package>
  <Objects>
    <Object Type="Package">moA</Object>
    <Object Type="Package">moB</Object>
    <Object Type="Package">moC</Object>
  </Objects>
</Package>

I want to solve this with LINQ, unfortunately I can't get the query to read the "Object" nodes as a collection for further processing.

var xdoc = XDocument.Load(inputFile);
var orderedList = xdoc.Root.Element("Objects");

CodePudding user response:

Try with this line, in order to select the Objects elements and order them :

var orderedList = xdoc.Root.Element("Objects")
                      .Elements("Object")
                      .OrderBy(e => e.Value);

Then you should create a new xElement to hold the sorted object elements and replace the original with the sorted version, and just save the modified doc!

CodePudding user response:

You can sort the objects and save them back to the file:

var objects = xdoc.Root.Element("Objects").Elements("Object");
var sortedObjects = objects.OrderBy(x => x.Value); // sort by inner text
xdoc.Root.Element("Objects").ReplaceNodes(sortedObjects); // replace with the sorted elements
xdoc.Save(inputFile); // save

If you want to keep the original, I'd suggest saving it to a different file.

  • Related