简体   繁体   中英

how to sort xml nodes

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");

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!

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.

You are only reading the root Objects , you need to read all the inner Object nodes:

var objectList = xdoc.Root.Element("Objects").Elements("Object");

You can then sort them by inner text:

var orderedList = objectList.OrderBy(x => x.Value); 

And replace the old Object nodes by the ordered ones:

xdoc.Root.Element("Objects").ReplaceNodes(orderedList);

Finally you can save them back to the file:

xdoc.Save(inputFile); // save

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

xdoc.Save("someOtherFile.xml"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM