如何使用 Powershell 3.0 注释掉 XML 节点?
How do you comment out an XML node using Powershell 3.0?
我想使用 Powershell 3.0 在配置文件中注释掉一个 XML 节点。
例如,如果这是我的 config.xml
文件:
<node>
<foo type="bar" />
</node>
我希望我的脚本将文件更改为:
<node>
<!-- <foo type="bar" /> -->
</node>
我希望使用 Powershell 3.0 的本机 XML/XPATH 功能来执行此操作,而不是 match/regex-based 字符串替换。
使用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
我想使用 Powershell 3.0 在配置文件中注释掉一个 XML 节点。
例如,如果这是我的 config.xml
文件:
<node>
<foo type="bar" />
</node>
我希望我的脚本将文件更改为:
<node>
<!-- <foo type="bar" /> -->
</node>
我希望使用 Powershell 3.0 的本机 XML/XPATH 功能来执行此操作,而不是 match/regex-based 字符串替换。
使用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