如何根据键值删除特定节点?

时间:2016-02-09 16:06:38

标签: xml powershell

任务是根据键或值删除节点,例如整个条目用键" org.quartz.B"和价值=" BBB"应该删除。

<config>
 <module>
   <section name="java">
    <entry key="org.quartz.A" value="AAA" />
    <entry key="org.quartz.B" value="BBB" />
    <entry key="org.quartz.C" value="CCC" />
    <entry key="org.quartz.D" value="false" />
   </section>
    <section name="db">
    <entry key="oracle" value="12" />
    <entry key="mssql" value="2012" />
    <entry key="mysql" value="6.1" />       
   </section>
 </module>
</config>

我尝试的代码是

$getxmlpath="C:\test.xml"
$xml=[xml](Get-Content $getxmlpath)
Write-Host ($xml)
$javasection = $xml.config.module | where-Object {$_.name -eq 'java'}
Write-Host ($javasection)
####### dont know how to delete particular node#######
$xml.Save($getxmlpath)

2 个答案:

答案 0 :(得分:1)

您可以使用XmlNode类的RemoveChild方法:

$childToRemove = $javaSection.entry | ? { $_.Key -eq 'org.quartz.B' }
$javaSection.RemoveChild($childToRemove)

请注意,使用它来查找要删除的元素是低效的,因为它必须使用Where-Object cmdlet过滤所有元素。如果您的xml很大,您可能希望使用类似于SelectSingleNode的方法来使用XPath表达式。

答案 1 :(得分:1)

我建议使用XPath表达式来查找匹配的节点:

$XPath = '//section[@name = "java"]/entry[@key = "org.quartz.B" and @value = "BBB"]'
$Nodes = $xml.SelectNodes($XPath)

然后,为了从文档中删除它们,您需要在每个节点的父级上调用RemoveChild()

foreach($Node in $Nodes)
{
    # RemoveChild() will return the child $Node 
    # We don't need it anymore, assign to $null
    $null = $Node.ParentNode.RemoveChild($Node)
}

# Save $xml
$xml.Save("C:\output.xml")