2012-03-13 15 views
2

私は今、非常に具体的な問題に直面しています。いくつかのデータをXMLDocumentに保存し、それをHDDに保存します。彼らはこのように見ている:.NET XMLDocumentエンコーディングの問題

<?xml version="1.0" encoding="utf-8"?> 
<Settings> 
    <Units> 
    <Unit> 
     <Name>Kilogramm</Name> 
     <ShortName>Kg</ShortName> 
    </Unit> 
    <Unit> 
     <Name>Flasche(n)</Name> 
     <ShortName>Fl</ShortName> 
    </Unit> 
    <Unit> 
     <Name>Stück</Name> 
     <ShortName>St</ShortName> 
    </Unit> 
    <Unit> 
     <Name>Beutel</Name> 
     <ShortName>Btl</ShortName> 
    </Unit> 
    <Unit> 
     <Name>Schale</Name> 
     <ShortName>Sch</ShortName> 
    </Unit> 
    <Unit> 
     <Name>Kiste</Name> 
     <ShortName>Ki</ShortName> 
    </Unit> 
    <Unit> 
     <Name>Meter</Name> 
     <ShortName>m</ShortName> 
    </Unit> 
    <Unit> 
     <Name>Stunde(n)</Name> 
     <ShortName>h</ShortName> 
    </Unit> 
    <Unit> 
     <Name>Glas</Name> 
     <ShortName>Gl</ShortName> 
    </Unit> 
    <Unit> 
     <Name>Portion</Name> 
     <ShortName>Port</ShortName> 
    </Unit> 
    <Unit> 
     <Name>Dose</Name> 
     <ShortName>Do</ShortName> 
    </Unit> 
    <Unit> 
     <Name>Paket</Name> 
     <ShortName>Pa</ShortName> 
    </Unit> 
    </Units> 
</Settings> 

I)は、(XMLDocument.Load経由でファイルをロードする)とXMLDocument.Save(とそれをsaveingよ。 しかし、私は古いPCからファイルを保存しましたが、保存して再読み込みした後、特殊文字(ä、ö、ü)の例外が発生しました。
実際にメモ帳でファイルを表示すると違いは表示されませんが、16進数で表示されるものはいくつかあります。これはどのように可能ですか?

+2

あなたの問題は、非常に具体的であれば、おそらくあなたは、より具体的なタイトルを使用するには、あなたの質問を編集できます?タイトル「.NET XmlDocument」を正確に使用するための[so]に関する100,000の質問があります。 –

+5

文書のエンコーディングをチェックしてください(**メモ帳**で開いて**名前を付けて保存**を実行して、エンコーディングの内容を確認してください)。 –

+0

@Adriano:正しいファイルにはUTF-8があり、もう1つはANSIです。しかし、なぜ彼らは同じコードで異なるのですか? – LastElb

答えて

4

保存する前に、このextensionmethodを使用してデコードを設定することができます。

/// <summary> 
/// Gets the XmlDeclaration if it exists, creates a new if not. 
/// </summary> 
/// <param name="xmlDocument"></param> 
/// <returns></returns> 
public static XmlDeclaration GetOrCreateXmlDeclaration(this XmlDocument xmlDocument) 
{ 
    XmlDeclaration xmlDeclaration = null; 
    if (xmlDocument.HasChildNodes) 
     xmlDeclaration = xmlDocument.FirstChild as XmlDeclaration; 

    if (xmlDeclaration != null) 
     return xmlDeclaration; 
    //Create an XML declaration. 
    xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", null, null); 

    //Add the new node to the document. 
    XmlElement root = xmlDocument.DocumentElement; 
    xmlDocument.InsertBefore(xmlDeclaration, root); 
    return xmlDeclaration; 
} 

用途:

XmlDeclaration xmlDeclaration = xmlDocument.GetOrCreateXmlDeclaration(); 
xmlDeclaration.Encoding = Encoding.UTF8.WebName; 
xmlDocument.Save(@"filename"); 
+0

を、私のために 'xmlDocument.InsertBerforeは()'この例外がスローされます: '挿入することはできません。指定された場所にノードを置く。私のXMLファイルは、通常のXML文書です。 –

0

あなたは直接宣言を追加することができます

var Doc = new XmlDocument(); 
Doc.AppendChild(Doc.CreateXmlDeclaration("1.0", "utf-8", null)); 
var productsNode = Doc.AppendChild(Doc.CreateElement("products")); 
//do other stuff