Remove XML Node

前端 未结 1 1468
臣服心动
臣服心动 2021-01-25 22:53

I have an XML file which contains a node that I wish to remove.


          


        
相关标签:
1条回答
  • 2021-01-25 23:14

    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($_)
    }
    
    0 讨论(0)
提交回复
热议问题