开发者

Sorting xml document in powershell

开发者 https://www.devze.com 2023-01-21 14:44 出处:网络
I\'d like to sort the following xml document using powershell. <car> <germany> <manufacturer>Opel</manufacturer>

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

精彩评论

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