Discussion:
Removing an XML node
(too old to reply)
Marco Shaw [MVP]
2009-01-22 00:58:47 UTC
Permalink
I have a large XML-formatted file that looks something like this:

<root>
<nodes>
<node tag="foo" name="bar">
<propertyvalue value="alpha"/>
</node>
<node tag="abc" name="xyz">
<propertyvalue value="gamma"/>
</node>
</nodes>
</root>

I'm struggling to to edit the file to remove this section:
<node tag="foo" name="bar">
<propertyvalue value="alpha"/>
</node>

Basically, I want to find any nodes with the string 'name="bar"'. When
found, I want to remove the entire <node>...</node> section, and
everything inside the tags.

I want to end up with:
<root>
<nodes>
<node tag="abc" name="xyz">
<propertyvalue value="gamma"/>
</node>
</nodes>
</root>

I can't seem to figure out an Xpath query to match this. I have tried:

$xml=[xml](get-content test.xml)
$xml.root.nodes.node|where{$_.name -eq "bar"}

I've tried a few of the methods available, but still can't seem to
remove the node this way either.

Any ideas?
--
*Microsoft MVP - Admin Frameworks
https://mvp.support.microsoft.com/profile/Marco.Shaw
*Co-Author - Sams Windows PowerShell Unleashed 2nd Edition (due December
15th, 2008)
*PowerShell Co-Community Director - http://www.powershellcommunity.org
*Blog - http://marcoshaw.blogspot.com
PaulChavez
2009-01-22 02:42:02 UTC
Permalink
Here's a method that seems to work on your test file.

$xml = (gc test.xml)
$delnodes = $xml.selectnodes("//node[@name='xyz']")
$delnodes | %{ $_.parentnode.removechild($_) }
$xml.save("$pwd\cleanfile.xml")

-Paul
Post by Marco Shaw [MVP]
<root>
<nodes>
<node tag="foo" name="bar">
<propertyvalue value="alpha"/>
</node>
<node tag="abc" name="xyz">
<propertyvalue value="gamma"/>
</node>
</nodes>
</root>
<node tag="foo" name="bar">
<propertyvalue value="alpha"/>
</node>
Basically, I want to find any nodes with the string 'name="bar"'. When
found, I want to remove the entire <node>...</node> section, and
everything inside the tags.
<root>
<nodes>
<node tag="abc" name="xyz">
<propertyvalue value="gamma"/>
</node>
</nodes>
</root>
$xml=[xml](get-content test.xml)
$xml.root.nodes.node|where{$_.name -eq "bar"}
I've tried a few of the methods available, but still can't seem to
remove the node this way either.
Any ideas?
--
*Microsoft MVP - Admin Frameworks
https://mvp.support.microsoft.com/profile/Marco.Shaw
*Co-Author - Sams Windows PowerShell Unleashed 2nd Edition (due December
15th, 2008)
*PowerShell Co-Community Director - http://www.powershellcommunity.org
*Blog - http://marcoshaw.blogspot.com
Loading...