删除XML节点 [英] Remove XML Node
问题描述
我有一个XML文件,其中包含要删除的< Notes>
节点。
I have an XML file which contains a <Notes>
node that I wish to remove.
<APPOrganisationUnits>
<APPOrganisationUnitsRow num="1">
<OrganisationId>TEST1</OrganisationId>
<APPContactDetails>
<APPContactDetailsRow num="1">
<Notes>Notes 1</Notes>
</APPContactDetailsRow>
<APPContactDetailsRow num="2">
<Notes>Notes 2</Notes>
</APPContactDetailsRow>
<APPContactDetailsRow num="3">
<Notes>Notes 3</Notes>
</APPContactDetailsRow>
</APPContactDetails>
</APPOrganisationUnitsRow>
<APPOrganisationUnitsRow num="2">
<OrganisationId>TEST2</OrganisationId>
<APPContactDetails>
<APPContactDetailsRow num="1">
<Notes>Notes 1</Notes>
</APPContactDetailsRow>
<APPContactDetailsRow num="2">
<Notes>Notes 2</Notes>
</APPContactDetailsRow>
</APPContactDetails>
</APPOrganisationUnitsRow>
</APPOrganisationUnits>
对于每个< notes> 节点,我只想删除它。我的代码可以运行但不会删除节点。
For each instance of the <notes>
node I just want to remove it. My code this which runs but does not remove the nodes.
$XMLFile = "$Provider_Root\Processing\small.xml"
$xml = [xml](Get-Content $XMLFile)
foreach ($APPContactDetailsRow in $xml.APPOrganisationUnits.APPOrganisationUnitsRow.APPContactDetails) {
if ($APPContactDetailsRow.Item('Notes')) {
$APPContactDetailsRow.RemoveChild($_)
}
}
$xml.Save($XMLFile)
}
推荐答案
当前对象变量( $ _
)未在循环上下文中填充。您需要先将子节点放入变量中,然后才能将其删除。另外,仅仅因为您在特定类型的节点后命名了变量,并不能通过该变量自动枚举节点。
The current object variable ($_
) isn't populated in the context of your loop. You need to put the child node into a variable before you can remove it. Also, Just because you name a variable after a particular type of nodes doesn't automagically enumerate the nodes via this variable. You need to actually expand the nodes.
更改此内容:
foreach ($APPContactDetailsRow in $xml.APPOrganisationUnits.APPOrganisationUnitsRow.APPContactDetails) {
if ($APPContactDetailsRow.Item('Notes')) {
$APPContactDetailsRow.RemoveChild($_)
}
}
变成这样:
foreach ($APPContactDetailsRow in $xml.APPOrganisationUnits.APPOrganisationUnitsRow.APPContactDetails.APPContactDetailsRow) {
$n = $APPContactDetailsRow.Item('Notes')
if ($n) {
$APPContactDetailsRow.RemoveChild($n)
}
}
这样,选择具有 XPath表达式并使用管道删除它们:
With that said, it'd probably be simpler to select the nodes with an XPath expression and use a pipeline for deleting them:
$xml.SelectNodes('//AppContactDetailsRow/Notes') | ForEach-Object {
$_.ParentNode.RemoveChild($_)
}
这篇关于删除XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!