tags:

views:

46

answers:

1

I'd like to sort the following xml document using powershell.

<car>
<germany>
    <manufacturer>Opel</manufacturer>
    <manufacturer>BMW</manufacturer>
    <manufacturer>Benz</manufacturer>
</germany>
<japan>
    <manufacturer>Nissan</manufacturer>
    <manufacturer>Daihatsu</manufacturer>
</japan></car>

So the elements inside germany and japan should be sorted.

Ideally I'd like to read the xml from the file system, and overwrite the existing doc with the sorted one.

+2  A: 

There are probably many solutions. One quick is this one:

$xml = [xml]"<car>
<germany>
    <manufacturer>Opel</manufacturer>
    <manufacturer>BMW</manufacturer>
    <manufacturer>Benz</manufacturer>
    <manufacturer>b</manufacturer>
    <manufacturer>a</manufacturer>
    <manufacturer>c</manufacturer>
</germany>
<japan>
    <manufacturer>Nissan</manufacturer>
    <manufacturer>Daihatsu</manufacturer>
</japan></car>"

$g = $xml.car.germany| select-xml 'manufacturer' | Select-Object -expand Node | sort '#text'
$j = $xml.car.japan | select-xml 'manufacturer' | Select-Object -expand Node | sort '#text'

@"
<car>
<germany>
    $( ($g | % { $_.OuterXml}) -join "`n`t" )
</germany>
<japan>
    $( ($j | % { $_.OuterXml}) -join "`n`t" )
</japan></car>
"@

Note that I used Select-Xml to extract manufacturers from the xml, because $xml.car.germany.manufacturer returned just array of strings (you probably had problems with that). I wasn't able to get the original object, even with help of PsBase property. That's why I used Select-Xml.

stej
What's wrong with using `$g = $xml.car.germany.manufacturer | sort`?
Keith Hill
`$xml.car.germany.manufacturer | sort` returns array of strings. Did you mean to recreate the xml like `$xml.car.germany.manufacturer | sort | % { '<manufacturer>'+$_+'</manufacturer>' }`? I found the `OuterXml` approach cleaner in case there would be some other attributes/elements inside. Or - are you able to get original `XmlElement` from `$xml.car.germany.manufacturer | sort`? I didn't :|
stej