XML sort order

Microsoft Windows
Post Reply
User avatar
Posts: 336
Joined: 2021-Jul-12, 1:37 pm

XML sort order

Post by MigrationUser »

03 Apr 2014 21:21


I am looking for a way to parse an xml file, alphabetize each node under root and then output to a new file while
keeping the xml formatting. my first attempts at this strips out the <> in the xml format

[xml]$xml = Get-Content "c:\location.xml"

$a = $xml.root.ChildNodes | Sort-Object
Write-Host $a

This seems to sort properly,but removes the <> around each node and i can't seem to export this using out-file or out-string.

Can someone help me with alphabetizing an xml file while keeping the formatting and eventually all of the children, with inner text, in order too?
At this point i am mainly concerned about the nodes under <Root>




#03 Apr 2014 22:00
Simon Sheppard

Look at Select-XML it will let you select the nodes of interest

Heres an example of sorting on stack overflow
https://stackoverflow.com/questions/3973 … powershell


#04 Apr 2014 14:06

I found these links already. It would be almost impossible to worry about 1 of the 500 sections of interest.
I really need to alphabetize all nodes between <Root> and </Root>. any ideas?


#08 Apr 2014 14:27

Any other insight on how to sort everything alphabetically between <Root> and </Root>? i can't seem to get select-xml to work properly. i am not opposed to using an xslt to sort with powershell either.

any help is appreciated.


#15 Apr 2014 15:29


so i am using this code

Code: Select all

$xml = @"
<?xml version="1.0" encoding="utf-8"?>
    <project name="Book2" date="20010-01-20">
        <edition language="English">En.Book2.com</edition>
        <edition language="German">Ge.Book2.Com</edition>
        <edition language="French">Fr.Book2.com</edition>
        <edition language="Polish">Pl.Book2.com</edition>
    <project name="Book1" date="2009-01-20">
        <edition language="English">En.Book1.com</edition>
        <edition language="German">Ge.Book1.Com</edition>
        <edition language="French">Fr.Book1.com</edition>
        <edition language="Polish">Pl.Book1.com</edition>

$xml | Select-Xml -XPath "//Roots" | foreach {$_.node.InnerXML} | sort | Out-File "$location" -Encoding utf8
from the example found here
https://docs.microsoft.com/en-gb/powers ... rshell-7.1

because i need <Root> to be included, i modified the example a bit.

The issue that i am having as you can expect is that the book and book2 are not alphabetical nor is any of the other xml nodes.
Can someone please help me understand what i am doing wrong.. it should not be this difficult to sort ALL xml nodes and children using powershell.


#16 Apr 2014 00:20

This MSDOS tool has sorting capability depending on various delimiters.

QSORT -- Version 4.11
Text File Sorting Utility
Copyright 1985-1989 - Ben Baker
Post Reply