繁体   English   中英

如何使用 Powershell 从 XML 中删除特殊/坏字符

[英]How to Remove Special/Bad Characters from XML Using Powershell

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

在此处输入图像描述

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

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

以下正则表达式将通过指定一个否定XML文档中整个有效unicode条目集的字符类来从XML中删除所有无效字符:

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

这可以很容易地变成一个简单的函数

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
}
# Another way, No 'Repair-XmlString' function needed, just wrap the string in single quotes
# This is an example of exporting install software names that have foreign characters. 

# Wrap output string with foreign characters in single quotes
$InstalledSoftware = Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\, HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\ |  Get-ItemProperty | select @{n="DisplayName";e={"\`'$($_.DisplayName)\`'"}}, DisplayVersion  

# Create Hastable
$SoftwareHashTable = @{SoftwareName = $InstalledSoftware }
# Output file path
$outFile = "$env:USERPROFILE\Desktop\HashFile.xml"   
# Export to hashtable xml                                                             
Export-Clixml -InputObject $SoftwareHashTable -Depth 4 -Path $outFile -Encoding UTF8 
# Import xml Hashtable
$ImportedXml = Import-Clixml $outFile    
# View values                                                                         
$ImportedXml.Values                                                                                               

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM