Comment XML section (having prefixes in the nodes) and un-comment other

后端 未结 1 454
没有蜡笔的小新
没有蜡笔的小新 2020-12-21 09:19

This is my sample xml data. Please ignore if there is any syntax error or some missing xml features. The task is to comment the above section and un-comment the below sectio

相关标签:
1条回答
  • 2020-12-21 09:45

    Something like this might work:

    [xml]$xml = Get-Content 'C:\Powershell\securityfile.xml'
    
    # create namespace manager
    $nsm = New-Object Xml.XmlNamespaceManager($xml.NameTable)
    $nsm.AddNamespace('dns', $xml.DocumentElement.dns)
    
    # remove nested comments from <auth-head> node(s)
    ($xml.SelectNodes('//dns:auth-head//comment()', $nsm)) | % {
      [void]$_.ParentNode.RemoveChild($_)
    }
    # comment-out node(s)
    ($xml.SelectNodes('//dns:auth-head', $nsm)) | % {
      $comment = $xml.CreateComment($_.OuterXml)
      [void]$_.ParentNode.ReplaceChild($comment, $_)
    }
    
    # uncomment <bean> node(s)
    ($xml.SelectNodes('//comment()')) | ? {
      $_.InnerText -like '*<bean*'
    } | % {
      $newxml = [xml]$_.InnerText
      $node = $xml.ImportNode($newxml.DocumentElement, $true)
      $node.SetAttribute('xmlns', $xml.DocumentElement.NamespaceURI)
      [void]$_.ParentNode.ReplaceChild($node, $_)
    }
    

    I was unable to find a way to re-insert the <bean> node without it getting an explict (empty) namespace attribute (xmlns=""), so I set that attribute to the default namespace of the XML document.

    Note that you must remove (or otherwise modify) the nested comments from the node you wish to comment out. Otherwise the closing --> from the first nested comment would prematurely terminate the comment node, leaving you with an invalid XML structure:

    <!--dns:auth-head alias="authHead">
        <dns:user-generator>    
            <dns:user-data>
    
                <!-- USER AA -->   # XML comment ends here!
                <dns:user name="AA"
                    password="AAAAAAAAAAAAAAAA" role="ROLE_AA" />
    
                <!-- USER BB -->
                <dns:user name="BB"
                    password="XXXXXXXXXXXXXXX" role="ROLE_BB" />
    
            </dns:user-data>       # tags from here on are invalid, because
        </dns:user-generator>      # they're missing their respective opening tag
    </dns:auth-head-->
    
    0 讨论(0)
提交回复
热议问题