问题
I have an XML:
<project>
<settings>
<setting1 name="s1">foo</setting1>
<setting2 name="s2">bar</setting2>
</settings>
<items>
<item name="a">
<property1>foo1</property1>
<property2>bar2</property2>
</item>
<item name="c">
<property1>foo3</property1>
<property2>bar4</property2>
</item>
<item name="b">
<property1>foo5</property1>
<property2>bar6</property2>
</item>
</items>
</project>
I need to sort the xml by attribute "name" of element "item".
I'm doing something like this:
[xml]$myXml = Get-Content -Encoding UTF8 $xmlPath
$myXml | Sort-Object {$_.project.items.item.name}
$myXml.Save($xmlPathSorted)
Is it possible to do it that easy in PS?
回答1:
Try this
# Get the items collection
$items = $myXml.project.items
# Sort the items and store in $orderedItems
$orderedItems = $items.item | Sort name
# Removed existing items from xml variable
$items.RemoveAll()
# Append sorted items
$orderedItems | foreach { $items.AppendChild($_) }
After running the above test with
$myxml.InnerXml
And you should see that the item
elements have been sorted.
来源:https://stackoverflow.com/questions/47343234/how-to-sort-xml-elements-in-powershell