Skip to content

Instantly share code, notes, and snippets.

@midnightfreddie
Last active March 8, 2016 06:56
Show Gist options
  • Save midnightfreddie/dd24e9401d1612db774e to your computer and use it in GitHub Desktop.
Save midnightfreddie/dd24e9401d1612db774e to your computer and use it in GitHub Desktop.
"`nWalking the XML tree`n"
$WeirdThingy = [xml](Get-Content "test.audit")
$RemoveNodes = @()
# Walk the nodes, match text and add nodes to $RemoveNodes array
$WeirdThingy.check_type.ChildNodes | ForEach-Object {
if ($_.InnerText -match '8.1.1.1') {
$RemoveNodes += $_
}
}
# Go through the $RemoveNodes array and remove them
# If I removed during the earlier ForEach loop, it skipped and confused the loop
$RemoveNodes | ForEach-Object {
$_.ParentNode.RemoveChild($_)
}
$WeirdThingy.OuterXml
# output:
# <check_type><custom_item>
# system : "Linux"
# type : "CHECK"
# description : "8.1.1.2 other text blah blah"
# </custom_item><custom_item>
# system : "Linux"
# type : "CHECK"
# description : "8.1.1.3 text blah blah"
# </custom_item></check_type>
"`nUsing Xpath`n"
$WeirdThingy = [xml](Get-Content "test.audit")
# Use Xpath query to match and return a list of nodes to remove, and remove them
$WeirdThingy.SelectNodes("//custom_item[contains(text(),'8.1.1.1')]") |
ForEach-Object {
$_.ParentNode.RemoveChild($_) | Out-Null
}
$WeirdThingy.OuterXml
# output:
# <check_type><custom_item>
# system : "Linux"
# type : "CHECK"
# description : "8.1.1.2 other text blah blah"
# </custom_item><custom_item>
# system : "Linux"
# type : "CHECK"
# description : "8.1.1.3 text blah blah"
# </custom_item></check_type>
<check_type>
<custom_item>
system : "Linux"
type : "CHECK"
description : "8.1.1.1 text blah blah"
</custom_item>
<custom_item>
system : "Linux"
type : "CHECK"
description : "8.1.1.2 other text blah blah"
</custom_item>
<custom_item>
system : "Linux"
type : "CHECK"
description : "8.1.1.1 more text blah blah"
</custom_item>
<custom_item>
system : "Linux"
type : "CHECK"
description : "8.1.1.3 text blah blah"
</custom_item>
</check_type>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment