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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With