【问题标题】:Converting xml from UTF-16 to UTF-8 using PowerShell使用 PowerShell 将 xml 从 UTF-16 转换为 UTF-8
【发布时间】:2010-10-19 12:34:58
【问题描述】:

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

【问题讨论】:

    标签: xml powershell utf-8 utf-16


    【解决方案1】:

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

    【讨论】:

    • 你不应该明确设置编码保存在某个地方吗?
    • 如果我知道怎么做,我会的。不过这似乎是默认设置。
    • @Exotic Hadron:不,除非它也是有效的 XML。
    【解决方案2】:

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

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

    这仅在没有 XML 时才有效

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

    行。

    【讨论】:

    • 如果你想在不创建新文件的情况下这样做,你可以将get-content括在括号中:(Get-Content File.foo) | Set-Content -Encoding UTF8 File.foo
    • 如何处理目录和子目录中的文件?
    • gci -rec -fi * | %{(gc $_ -enc unicode) | set-content -enc utf8 $_.fullname}。实际上相当简单。
    • @Joey,对你的 powershell 脚本的一个小修正...gci -rec -fi * | %{(gc $_.fullname -enc unicode) | set-content -enc utf8 $_.fullname}
    • 那里不需要使用FullNameGet-Content 知道如何处理 FileInfo
    【解决方案3】:

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

    【讨论】:

    • 非常感谢您关心为这样一个老问题提供如此简短、技术上更好的答案!
    • 我必须完成它,甚至在看到这个问题之前我就找到了这个解决方案。我觉得提供它是正常的。甚至可以在转换文件编码的同时使用它进行复制。问候。
    猜你喜欢
    • 2015-09-19
    • 2015-09-21
    • 2013-04-11
    • 2013-05-20
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 2019-05-15
    相关资源
    最近更新 更多