Harvey
Harvey

Reputation: 1408

PowerShell Script to Delete XML Element

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:

^^ 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

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

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

Related Questions