powershell - 如何使用 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 功能来执行此操作,而不是基于匹配/正则表达式的字符串替换。
解决方案
用于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
推荐阅读
- python - Cassandra:根据非主键删除记录 - Python
- angular - 如何在 GoDaddy 上托管 Angular-CLI 项目?
- node.js - 如何使用 socket.io 将 tcp 消息发送到远程服务器
- javascript - 如何相对于底层图像绝对定位形状元素?
- python - How to add numpy matrix as new columns for pandas dataframe?
- mysql - 使用 Node.js 搜索 PDF 文本
- mysql - using GROUP_CONCAT in MySQL Transaction
- javascript - Passing .NET Core Environment to React.JS app
- javascript - What is wrong with my JSON in this Oauth Request?
- webpack - Is there a way to make Webpack less verbose INSIDE the bundle?