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

Converting xml from UTF-16 to UTF-8 using PowerShell

将XML从UTF16转换为UTF8编码的文件的最简单方法是什么?


好吧,我想最简单的方法就是不关心文件是否是XML,而只是转换:

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

只有在没有XML的情况下,这才适用于XML

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

线。


这可能不是最佳选择,但它可以工作。 只需加载xml并将其推回文件即可。 xml标题虽然丢失了,所以必须重新添加。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$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的此解决方案:

1
2
3
4
5
6
7
8
$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的更多说明。