2

I'm adding related elements (Parent-Child) through an XML file using the following:

[xml]$fileXml = Get-Content 'c:\example.xml'

$fileXml.Elements | % {
  MyAdd-Function $_
}

When deleting these elements, how do I make sure it iterates in the reverse order? I've tried this and it doesn't work:

[xml]$fileXml = Get-Content 'c:\example.xml'

[Array]::Reverse($fileXml.Elements) | % {
  MyRemove-Function $_
}

I'm thinking about turning $fileXml.Elements into an actual array and then reversing, but I was wondering if there's an easier way.

1 Answer 1

1

Your approach sounds good to me, but considering that Reverse() doesn't return an array, you would have to split Reverse() and Foreach-Object.

PS > [array]::Reverse.OverloadDefinitions
static void Reverse(array array)

I'm not sure where you got the Elements-property from, but here's a PoC:

PS > $xml = [xml]@"
<?xml version="1.0" encoding="UTF-8"?>
<root>
<note>
<to>User1</to>
</note>
<note>
<to>User2</to>
</note>
</root>
"@

#Store the elements in an array 
PS > $a = $xml.root.note
PS > $a | % { $_.to }

User1
User2

#Reverse
PS > [array]::Reverse($a)
PS > $a | % { $_.to }

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

1 Comment

Awesome! That worked! I guess I need to store it into a variable first c:

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.