0

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 Answer 1

2

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.

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

1 Comment

$orderedItems = $items.item | Sort name; returns nothing. Sort is an alias of Sort-Object.

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.