I have an XML file which contains a
node that I wish to remove.
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.
Change this:
foreach ($APPContactDetailsRow in $xml.APPOrganisationUnits.APPOrganisationUnitsRow.APPContactDetails) {
if ($APPContactDetailsRow.Item('Notes')) {
$APPContactDetailsRow.RemoveChild($_)
}
}
into this:
foreach ($APPContactDetailsRow in $xml.APPOrganisationUnits.APPOrganisationUnitsRow.APPContactDetails.APPContactDetailsRow) {
$n = $APPContactDetailsRow.Item('Notes')
if ($n) {
$APPContactDetailsRow.RemoveChild($n)
}
}
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($_)
}