最简单的将XML从UTF16转换成UTF8编码的方法是什么?
嗯,我想最简单的方法就是不用关心文件是否为XML,直接进行转换:
Get-Content file.foo -Encoding Unicode | Set-Content -Encoding UTF8 newfile.foo
当XML中不存在时,这只适用于XML。
<?xml version="1.0" encoding="UTF-16"?>
行。
这可能不是最优的方法,但它是可行的。只需加载xml并将其推回到文件中即可。不过,xml标题会丢失,因此必须重新添加。
$files = get-ChildItem "*.xml"
foreach ( $file in $files )
{
[System.Xml.XmlDocument]$doc = new-object System.Xml.XmlDocument;
$doc.set_PreserveWhiteSpace( $true );
$doc.Load( $file );
$root = $doc.get_DocumentElement();
$xml = $root.get_outerXml();
$xml = '<?xml version="1.0" encoding="utf-8"?>' + $xml
$newFile = $file.Name + ".new"
Set-Content -Encoding UTF8 $newFile $xml;
}
尝试使用 XmlWriter
的这个解决方案:
$encoding="UTF-8" # most encoding should work
$files = get-ChildItem "*.xml"
foreach ( $file in $files )
{
[xml] $xmlDoc = get-content $file
$xmlDoc.xml = $($xmlDoc.CreateXmlDeclaration("1.0",$encoding,"")).Value
$xmlDoc.save($file.FullName)
}
XMLDocument
以获取有关 CreateXmlDeclaration
的更多说明。
gci -rec -fi * | %{(gc $_.fullname -enc unicode) | set-content -enc utf8 $_.fullname}
- Tim FriesenFullName
。Get-Content
知道如何处理FileInfo
。 - Joey