【问题标题】:How do you comment out an XML node using Powershell 3.0?如何使用 Powershell 3.0 注释掉 XML 节点?
【发布时间】:2020-03-24 18:52:31
【问题描述】:

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

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

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

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

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

我希望使用 Powershell 3.0 的原生 XML/XPATH 功能来执行此操作,而不是基于匹配/正则表达式的字符串替换。

【问题讨论】:

    标签: powershell powershell-3.0


    【解决方案1】:

    使用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])的详细信息。我最终需要一种方法来取消注释节点 - 希望自己找到这些信息。
    猜你喜欢
    • 2013-05-25
    • 1970-01-01
    • 2012-07-19
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多