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
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 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 node(s)
($xml.SelectNodes('//comment()')) | ? {
$_.InnerText -like '*
I was unable to find a way to re-insert the
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:
# XML comment ends here!
# tags from here on are invalid, because
# they're missing their respective opening tag