Reputation: 1408
I have an XML doccument that looks like this:
<Task>
<Settings>
</Settings>
<Sub>foo</Sub>
<Body>bar</Body>
</Task>
From PowerShell I can happily get the contents of 'Sub' and 'Body' using:
$Body = $XMLFile.Task.Body
But I am trying to REMOVE the 'Sub' and 'Body' Tags completely so the XML would be:
<Task>
<Settings>
</Settings>
</Task>
I have already Tried many things, Including:
.RemoveChild()
method (Threw an exeption relating to Object reference)Even opening the file as a text file and trying:
Get-Content $_.FullName -notmatch "<Sub>" | out-file $_.FullName
^^ This does nothing at all
Also for this application of script I would be unable to use any third party modules
Upvotes: 7
Views: 21187
Reputation: 174485
You can use Where-Object
to find the Child nodes you want to remove and then call RemoveChild()
:
$Input = "C:\path\task.xml"
$Output = "C:\path\newtask.xml"
# Load the existing document
$Doc = [xml](Get-Content $Input)
# Specify tag names to delete and then find them
$DeleteNames = "Sub","Body"
($Doc.Task.ChildNodes |Where-Object { $DeleteNames -contains $_.Name }) | ForEach-Object {
# Remove each node from its parent
[void]$_.ParentNode.RemoveChild($_)
}
# Save the modified document
$Doc.Save($Output)
Upvotes: 12