Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • Using the .RemoveChild() method (Threw an exeption relating to Object reference)
  • Removing with an XPath Statement and adding a Pipe to remove in one line
  • 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

like image 856
Harvey Avatar asked Jul 17 '15 14:07

Harvey


People also ask

How to remove an element from XML PowerShell?

To delete the specific XML node from the PowerShell, we can use the RemoveChild() method of the XML.

How do you delete an element in XML?

In the XML Files explorer, right-click the XML file or XML element that you want to remove and click Delete.

What is XML in PowerShell?

Introduction to PowerShell XML. Extensible Markup Language (XML) is a soft, light-weighted markup language like HTML that defines the set of rules for encoding documents in a format that is both human-readable and machine-readable and used to store and transport data.


1 Answers

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)
like image 164
Mathias R. Jessen Avatar answered Oct 05 '22 11:10

Mathias R. Jessen