2014-10-17 171 views
2
<?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 ......這是我到目前爲止有:使用Powershell刪除節點

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

回答

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

,或者你可以使用XML PowerShell的內置支持:

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

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

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

由於xml文檔命名空間已從xmlns =「tnw:grc:import:people」更新爲xmlns =「TestData」 – DanL 2014-10-17 14:58:40

+0

感謝Dan!這很好,但我確實注意到它只是從第一個Person中刪除主管...我沒有將它包含在上面的XML文檔中,但我有多個人希望刪除此節點。 – mpalatsi 2014-10-17 17:31:55