首页 > 解决方案 > 如何使用 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 功能来执行此操作,而不是基于匹配/正则表达式的字符串替换。

标签: powershellpowershell-3.0

解决方案


用于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

推荐阅读