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

时间:2009-04-15 05:45:07

标签: xml powershell utf-8 utf-16

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

3 个答案:

答案 0 :(得分:14)

这可能不是最优的,但它确实有效。只需加载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;
}

答案 1 :(得分:14)

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

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

这只适用于没有

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

线。

答案 2 :(得分: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的更多说明。

相关问题