将 XML 从 UTF16 转换为 UTF8 编码文件的最简单方法是什么?
问问题
22276 次
3 回答
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;
}
于 2009-04-15T05:49:54.553 回答
16
好吧,我想最简单的方法是不关心文件是否是 XML 并简单地转换:
Get-Content file.foo -Encoding Unicode | Set-Content -Encoding UTF8 newfile.foo
这仅适用于 XML 时没有
<?xml version="1.0" encoding="UTF-16"?>
线。
于 2011-01-27T14:37:47.657 回答
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
.
于 2012-06-07T13:37:52.550 回答