如何使用Powershell 3.0注释XML节点



我想使用Powershell 3.0注释掉配置文件中的一个XML节点。

例如,如果这是我的config.xml文件:

<node>
<foo type="bar" />
</node>

我希望我的脚本将文件更改为:

<node>
<!-- <foo type="bar" /> -->
</node>

我希望使用Powershell 3.0的原生XML/XPATH功能来实现这一点,而不是基于匹配/regex的字符串替换。

使用CreateComment()创建一个包含现有节点的XML的新注释节点,然后删除现有的:

$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

最新更新