Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell : sort xml by elements by child node value

Tags:

powershell

xml

How to sort descending this xml by the second node of this list of "Tuple" (the "integer" typed) using Powershell.

So the result would be xml but the first element would be COMPUTERSF34, then COMPUTER123..

   <Result>
                <Tuple>
                    <Answer type="string">COMPUTERSF34</Answer>
                    <Answer type="integer">93</Answer>
                </Tuple>
                <Tuple>
                    <Answer type="string">NYCCOMPUTER01</Answer>
                    <Answer type="integer">44</Answer>
                </Tuple>
                <Tuple>
                    <Answer type="string">COMPUTER_05</Answer>
                    <Answer type="integer">45</Answer>
                </Tuple>
                <Tuple>
                    <Answer type="string">COMPUTER56</Answer>
                    <Answer type="integer">38</Answer>
                </Tuple>
                <Tuple>
                    <Answer type="string">COMPUTER123</Answer>
                    <Answer type="integer">51</Answer>
                </Tuple>
    ...
    </Result>
like image 931
Patrick P Avatar asked Dec 09 '25 20:12

Patrick P


1 Answers

Try this:

$xml = [xml]@'
   <Result>
                <Tuple>
                    <Answer type="string">COMPUTERSF34</Answer>
                    <Answer type="integer">93</Answer>
                </Tuple>
                <Tuple>
                    <Answer type="string">NYCCOMPUTER01</Answer>
                    <Answer type="integer">44</Answer>
                </Tuple>
                <Tuple>
                    <Answer type="string">COMPUTER_05</Answer>
                    <Answer type="integer">45</Answer>
                </Tuple>
                <Tuple>
                    <Answer type="string">COMPUTER56</Answer>
                    <Answer type="integer">38</Answer>
                </Tuple>
                <Tuple>
                    <Answer type="string">COMPUTER123</Answer>
                    <Answer type="integer">51</Answer>
                </Tuple>
    </Result>
'@
$sorted = $xml.Result.Tuple | sort {[int]$_.Answer[1].'#text'} -desc
$lastChild = $sorted[-1]
$sorted[0..($sorted.Length-2)] | Foreach {$xml.Result.InsertBefore($_,$lastChild)}
$xml.Save('c:\foo.xml')

The trick is to take each of the sorted nodes (except the last) and insert it before the new (post-sort) last node.

like image 82
Keith Hill Avatar answered Dec 11 '25 11:12

Keith Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!