I have a 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:
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 node Objects
, this will give an XElement
object and not a collection, you need to read all the inner Object
nodes:
var objectList = xdoc.Root.Element("Objects").Elements("Object");
The result is an IEnumerable<XElement>
which you can manipulate with LINQ.
I want to sort the
Object
nodes alphabetically and write them back to the file.
When you have the collection of Object
you can sort it by the 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);
After that it's just a matter of saving this back to the file:
xdoc.Save(inputFile); // will replace the content
If you want to keep the original just save this to a different file:
xdoc.Save("someOtherFile.xml");
Here you have a run of the described program, showing the file before and after:
Side note:
Be aware that you have non-printable characters in the posted xml content that will break your program:
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!