使用PowerShell将XML从UTF-16转换为UTF-8

19
最简单的将XML从UTF16转换成UTF8编码的方法是什么?
3个回答

16

嗯,我想最简单的方法就是不用关心文件是否为XML,直接进行转换:

Get-Content file.foo -Encoding Unicode | Set-Content -Encoding UTF8 newfile.foo

当XML中不存在时,这只适用于XML。

<?xml version="1.0" encoding="UTF-16"?>

行。


6
如果你不想创建一个新文件,可以在括号中包裹"Get-Content":(Get-Content File.foo) | Set-Content -Encoding UTF8 File.foo。该操作将原文件内容重新编码为UTF8格式。 - Jaykul
你如何在目录及其子目录中处理文件? - stormwild
2
"gci -rec -fi * | %{(gc $_ -enc unicode) | set-content -enc utf8 $_.fullname}"。实际上非常简单。 - Joey
@Joey,你 PowerShell 脚本有一个小错误... gci -rec -fi * | %{(gc $_.fullname -enc unicode) | set-content -enc utf8 $_.fullname} - Tim Friesen
1
不需要在那里使用 FullNameGet-Content 知道如何处理 FileInfo - Joey
显示剩余2条评论

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;
}

你不应该在保存时明确设置编码吗? - Joey
如果我知道怎么做,我会尝试的。但这似乎是默认设置。 - Ben Laan
@Exotic Hadron:不,除非它也是有效的XML。 - Joey

9

尝试使用 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 的更多说明。

非常感谢您关心并提供了如此简明、技术更好的答案,尤其是对于这样一个老问题! - gimpf
我必须完成它,甚至在看到这个问题之前就找到了这个解决方案。我觉得提供它很正常。有人只需花费一点努力,甚至可以使用它来复制文件并转换编码。问候。 - LMA1980

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接