PowerShell Script to Delete XML Element -


i have xml doccument looks this:

<task>     <settings>     </settings>     <sub>foo</sub>     <body>bar</body> </task> 

from powershell can happily contents of 'sub' , 'body' using:

$body = $xmlfile.task.body 

but trying remove 'sub' , 'body' tags xml be:

<task>     <settings>     </settings> </task> 

i have tried many things, including:

  • using .removechild() method (threw exeption relating object reference)
  • removing xpath statement , adding pipe remove in 1 line
  • even opening file text file , trying:

    get-content $_.fullname -notmatch "<sub>" | out-file $_.fullname

^^ nothing @ all

also application of script unable use third party modules

you can use where-object find child nodes want remove , call removechild():

$input = "c:\path\task.xml" $output = "c:\path\newtask.xml"  # load existing document $doc = [xml](get-content $input)  # specify tag names delete , find them $deletenames = "sub","body" ($doc.task.childnodes |where-object { $deletenames -contains $_.name }) | foreach-object {     # remove each node parent     [void]$_.parentnode.removechild($_) }  # save modified document $doc.save($output) 

Comments