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
To delete the specific XML node from the PowerShell, we can use the RemoveChild() method of the XML.
In the XML Files explorer, right-click the XML file or XML element that you want to remove and click Delete.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With