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

发布于 2024-07-17 06:32:49 字数 44 浏览 5 评论 0原文

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

What's the easiest way to convert XML from UTF16 to a UTF8 encoded file?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

尹雨沫 2024-07-24 06:32:49

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

This may not be the most optimal, but it works. Simply load the xml and push it back out to a file. the xml heading is lost though, so this has to be re-added.

$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;
}
倾城°AllureLove 2024-07-24 06:32:49

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

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

这仅适用于没有行

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

的 XML 。

Well, I guess the easiest way is to just not care about whether the file is XML or not and simply convert:

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

This will only work for XML when there is no

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

line.

诗化ㄋ丶相逢 2024-07-24 06:32:49

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

Try this solution that uses a 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)      
}

You may want to look at XMLDocument for more explanation on CreateXmlDeclaration.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文