如何在PowerShell中对XML元素进行排序

时间:2017-11-17 04:19:53

标签: xml powershell

我有一个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中是否可以轻松实现?

1 个答案:

答案 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元素已经排序。