开发者

Sorting xml document in powershell

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

<car>
<germany>
    <manufacturer>Opel</manufacturer>
    <manufacturer>BMW</manufacturer>
    <manufacturer>Benz</manufa开发者_如何学JAVActurer>
</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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜