Using Powershell to Delete Node

Question!
  <?xml version="1.0" encoding="UTF-8"?>
    <People xmlns="TestData">
      <Person Id="TestData" Status="TestData">
        <Name>
          <FirstName>TestData</FirstName>
          <LastName>TestData</LastName>
        </Name>
        <Dimensions>
          <Dimension Id="TestData" Name="TestData" Dimension="TestData" />
          <Dimension Id="TestData" Name="TestData" Dimension="TestData" />
          <Dimension Id="TestData" Name="TestData" Dimension="TestData" />
          <Dimension Id="TestData" Name="TestData" Dimension="TestData"/>
        </Dimensions>
        <EmploymentInformation>
          <DateHired>TestData</DateHired>
          <DateRehired>TestData</DateRehired>
          <EmployeeStatus>TestData</EmployeeStatus>
          <JobCode>TestData</JobCode>
          <Supervisor Id="TestData" Name="TestData" />
          <Title>TestData</Title>
        </EmploymentInformation>
      </Person>
    </People>

My XML document is above. I would like to remove the node 'Supervisor' under 'EmploymentInformation'. I'm having some trouble putting together my XPath... This is what I have so far:

[xml]$xml = gc C:\Users\username\Downloads\Test.xml

$supervisor = $xml.SelectSingleNode('//People/Person/EmploymentInformation/Supervisor')
$employmentInformation = $xml.SelectSingleNode('//People/Person/EmploymentInformation')
[void]$employmentInformation.RemoveChild($supervisor)
$xml.Save('C:\Users\username\Downloads\Result.xml')
By : mpalatsi


Answers

Hi you have a namespace defined on your XML document but don't qualify your XPath. Do something like the following:

[xml]$xml = gc C:\Users\username\Downloads\Test.xml

$mgr = New-Object -TypeName System.Xml.XmlNamespaceManager -ArgumentList $xml.NameTable
$mgr.AddNamespace("bob","TestData")

$supervisor = $xml.SelectSingleNode('//bob:People/bob:Person/bob:EmploymentInformation/bob:Supervisor', $mgr)
$employmentInformation = $xml.SelectSingleNode('//bob:People/bob:Person/bob:EmploymentInformation', $mgr)
[void]$employmentInformation.RemoveChild($supervisor)
$xml.Save('C:\Users\username\Downloads\Result.xml')

If you want to do this with multiple people then the following should do it:

[xml]$xml = gc .\Test.xml

$mgr = New-Object -TypeName System.Xml.XmlNamespaceManager -ArgumentList $xml.NameTable
$mgr.AddNamespace("bob","TestData")

$supervisors = $xml.SelectNodes('//bob:People/bob:Person/bob:EmploymentInformation/bob:Supervisor', $mgr)

foreach ($supervisor in $supervisors)
{
        $supervisor.ParentNode.RemoveChild($supervisor)
}

$xml.Save('.\Result.xml')

or you could use Powershell's builtin support for XML:

[xml]$xml = gc .\Test.xml

foreach ($supervisor in $xml.People.Person.EmploymentInformation.Supervisor)
{
        $supervisor.ParentNode.RemoveChild($supervisor)
}

$xml.Save('.\Result.xml')
By : DanL


This video can help you solving your question :)
By: admin