【问题标题】:Remove XML string within a file删除文件中的 XML 字符串
【发布时间】:2017-05-14 15:13:02
【问题描述】:

我需要一个在 XML 文件中搜索 <?xml version="1.0" encoding="UTF-8"?> 并将其删除的 PowerShell 脚本。 我试过了:

(Get-Content $file) | 
    Foreach { $_ -Replace  '<?xml version="1.0" encoding="UTF-8"?>', "" } | 
    Set-Content $file;

但它不起作用。

【问题讨论】:

    标签: xml powershell replace


    【解决方案1】:

    你也可以像这样转义你的字符串

    (Get-Content $file) | 
        Foreach { $_ -Replace  [Regex]::Escape('<?xml version="1.0" encoding="UTF-8"?>'), '' } | 
            Set-Content $file;
    

    【讨论】:

      【解决方案2】:

      @MartinBrandl's answer 的基础上,如果您需要删除多个部分,您可以这样做:

      $toRemove = '</Export>', '<Export/>', '<?xml version="1.0" encoding="UTF-8"?>'
      
      $content = Get-Content $file -Raw
      
      foreach($part in $toRemove) {
          $content = $content.Replace($part, '')
      }
      
      $content | Set-Content $file
      

      【讨论】:

        【解决方案3】:

        这不起作用,因为-replace 使用正则表达式(您必须转义字符串才能使其工作)。但是,您也可以将.Replace 静态方法用于不使用正则表达式的字符串

        (Get-Content $file -raw).Replace('<?xml version="1.0" encoding="UTF-8"?>', '') | 
            Set-Content $file;
        

        请注意,我使用Get-Content cmdlet 的-raw 开关将文件加载为单个字符串(而不是字符串数组)-因此您无需遍历行但可以替换所有内容一次。

        【讨论】:

        • 例如删除(Get-Content $output -raw).Replace('&lt;/Export&gt;', '') | Set-Content $output;(Get-Content $output -raw).Replace('&lt;Export/&gt;', '') | Set-Content $output;(Get-Content $output -raw).Replace('&lt;?xml version="1.0" encoding="UTF-8"?&gt;', '') | Set-Content $output; 有没有更简单的方法?
        • @MartinhoVasconcelos 您正在更改 cmets 中的要求。请坚持您的第一个问题,因为接受的答案与您的问题不匹配。如果这很重要,您应该首先将edited 到问题中。
        • 您可以将多个替换连接在一起,例如:(Get-Content $output -raw).Replace('&lt;/Export&gt;', '').Replace('&lt;Export/&gt;', '').Replace(....) | Set-Content $output。但由于您正在编辑 XML,最好使用 XML 方法来执行此操作(取决于您的要求)。
        • -raw 在这里没有用,因为你使用 ()
        • @Esperento57 没错,没必要
        猜你喜欢
        • 2011-03-19
        • 2012-10-08
        • 1970-01-01
        • 1970-01-01
        • 2018-11-20
        • 1970-01-01
        • 1970-01-01
        • 2014-12-19
        相关资源
        最近更新 更多