如何使用 Powershell 从 XML 中删除 Special/Bad 个字符

How to Remove Special/Bad Characters from XML Using Powershell

我有一个 XML 文件,我想从以下文件中删除那些十六进制字符错误是无效字符:

我不知道 STX 是什么意思,当我尝试将它复制到我的剪贴板并将其粘贴到 MS Work 中时,它显示了一些其他值。

如何在 powershell 中编写脚本以从我的 XML 文件中删除上述内容。

以下正则表达式将通过指定字符 class 否定 XML 文档中的整组有效 unicode 条目来删除 XML 中的任何无效字符:

$rPattern = "[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000\x10FFFF]"
$xmlText -replace $rPattern,''

这很容易变成 a simple function:

function Repair-XmlString
{
  [CmdletBinding()]
  param(
    [Parameter(Mandatory=$true,Position=0)]
    [string]$inXML
  )

  # Match all characters that does NOT belong in an XML document
  $rPattern = "[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000\x10FFFF]"

  # Replace said characters with [String]::Empty and return
  return [System.Text.RegularExpressions.Regex]::Replace($inXML,$rPattern,"")
}

然后做:

Repair-XmlString (Get-Content path\to\file.xml -Raw) |Set-Content path\to\file.xml 

功能更新:)

function Repair-XmlString {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true, Position = 0,ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [string]$String
    )
    Write-Host "Cleaning string for XML parsing [String: $($String)]"
    $rPattern = "[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000\x10FFFF]"
    $cleaned = $String -replace $rPattern, ''
    Write-Host "Returning parsed string [String cleaned: $($cleaned)]"
    return $cleaned
}