Something like this might work:
[xml]$xml = Get-Content 'C:Powershellsecurityfile.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-->
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…