使用Powershell删除节点

时间:2014-10-17 14:22:12

标签: xml powershell xpath

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

我的XML文档在上面。我想删除'EmploymentInformation'下的节点'Supervisor'。我在整理XPath时遇到了一些麻烦......这就是我到目前为止所做的:

[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')

1 个答案:

答案 0 :(得分:0)

您是否在XML文档中定义了命名空间,但没有资格获得XPath。做类似以下的事情:

[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')

如果您想与多人合作,则应执行以下操作:

[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')

或者您可以使用Powershell对XML的内置支持:

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

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

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