سؤال

ما هي أسهل طريقة لتحويل XML من UTF16 إلى ملف مشفر UTF8؟

هل كانت مفيدة؟

المحلول

قد لا يكون هذا هو الأكثر الأمثل، لكنه يعمل. ما عليك سوى تحميل 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;
}

نصائح أخرى

حسنا، أعتقد أن أسهل طريقة هي عدم الرعاية فقط إذا كان الملف XML أم لا وتحويل ببساطة:

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

هذا سوف يعمل فقط من أجل XML عندما لا يكون هناك

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

خط.

جرب هذا الحل الذي يستخدم 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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top