4

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
  • Where does the <car> tag start and end? Commented Oct 20, 2010 at 0:08
  • Oops!!! Forgot about that, sorry. Right after </japan> Commented Oct 20, 2010 at 0:13

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What's wrong with using $g = $xml.car.germany.manufacturer | sort?
$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 :|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.