![](/img/trans.png)
[英]How to remove special characters while saving xml string using Powershell
[英]How to Remove Special/Bad Characters from XML Using Powershell
以下正则表达式将通过指定一个否定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.