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"?> |
线。
-
如果要在不创建新文件的情况下执行此操作,则可以将get-content包装在括号中:(Get-Content File.foo)|设置内容编码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}
-
无需在那里使用FullName。 Get-Content知道如何处理FileInfo。
-
@Joey,对我来说不幸的是,它抱怨找不到路径。我认为它必须将FileInfo对象转换为字符串。 Get-Content : Cannot find path C:\WorkingFolder\FileName.txt because it does not exist. At line:1 char:26 + gci -rec -fi *.txt | %{(gc <<<< $_ -enc ascii) | set-content -enc utf8 $_.fullname} + CategoryInfo : ObjectNotFound: (C:\WorkingFolder\FileName.txt:String) [Get-Content], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand FileName.txt位于C: WorkingFolder的子文件夹中。
这可能不是最佳选择,但它可以工作。 只需加载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;
} |
-
您是否应该明确设置编码以保存在某处?
-
如果我知道怎么做,我会的。它似乎是默认设置。
-
@Exotic Hadron:否,除非它也是有效的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的更多说明。
-
非常感谢您愿意提供这样一个简短,技术上更好的答案,以回答如此古老的问题!
-
我不得不完成它,甚至在看到这个问题之前就找到了这个解决方案。我觉得提供它是正常的。在转换文件编码时,有人甚至可以毫不费力地使用它进行复制。问候。