我有一个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>
我需要按属性排序xml&#34; name&#34;元素&#34;项目&#34;。
我做这样的事情:
[xml]$myXml = Get-Content -Encoding UTF8 $xmlPath
$myXml | Sort-Object {$_.project.items.item.name}
$myXml.Save($xmlPathSorted)
PS中是否可以轻松实现?
答案 0 :(得分:1)
试试这个
# 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($_) }
用
运行上述测试后$myxml.InnerXml
您应该看到item
元素已经排序。