I would like to comment out an XML node in a configuration file using Powershell 3.0.
For instance, if this is my config.xml
file:
<node>
<foo type="bar" />
</node>
I would like my script to change the file to this:
<node>
<!-- <foo type="bar" /> -->
</node>
I am looking to do this using Powershell 3.0's native XML/XPATH functionality, and not match/regex-based string replacement.
Use CreateComment()
to create a new comment node containing the existing node's XML, then remove the existing:
$xml = [xml]@'
<node>
<foo type="bar" />
</node>
'@
# Find all <foo> nodes with type="bar"
foreach($node in $xml.SelectNodes('//foo[@type="bar"]')){
# Create new comment node
$newComment = $xml.CreateComment($node.OuterXml)
# Add as sibling to existing node
$node.ParentNode.InsertBefore($newComment, $node) |Out-Null
# Remove existing node
$node.ParentNode.RemoveChild($node) |Out-Null
}
# Export/save $xml