powershell xml sort nodes and replacechild

Question:

I’m trying to do something pretty simple with powershell and xml but haven’t a bit of trouble.
Basically I’m trying to take the following xml… and sort the machine elements by name. Then put them back into the XML so that I can save back to a file.

Sorting seems to be working if output the $new object however, during the replacechild it’s complaining “Cannot convert argument “0”, with value: “System.Object[]” for “ReplaceChild” to type “System.Xml.XmlNode” : “Cannot convert the “System.Object[]” to type “System.Xml.XmlNode”.

If I do a Get-Member on both $orig and $new they both say they are of type XMLElement which I believe inherits from XMLNode.

What am I missing guys? Driving me nuts. Thanks for your help!

Answer:

There are various problems here. One is that your sort returns a list of xml elements rather than a single xml element. Another problem is that it returns the original xml elements rather than copies, so any manipulation of the xml DOM that you do using them will also affect the result.

Here’s a simple way to get what you want. Sort in reverse order, and then insert each node in turn in front of the others. Each time you insert a node from the result of the sort it will automatically remove it from the original set of node:


Edit: The pipeline can also be written with an ascending sort (as David Martin pointed out), and you can reduce typing by using the node in the variable:

Source:

powershell xml sort nodes and replacechild by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply