2012-03-13 88 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> 

我通過XMLDocument.load方法加載文件(),並與XMLDocument.Save saveing它()。 但現在我保存了舊PC上的文件,現在我保存並重新加載後,在特殊字符(ä,ö,ü)上出現異常。
事實上,在記事本中查看文件顯示沒有區別,但在十六進制查看有一些!這怎麼可能?

+2

如果你的問題是非常具體的,那麼也許你可以編輯你的問題用一個更具體的標題? [所以]必須有10萬個問題準確地使用標題「.NET XmlDocument」。 – 2012-03-13 16:14:12

+5

檢查文件編碼(只需用**記事本打開**並執行**另存爲**以查看它提供的編碼)。 – 2012-03-13 16:16:48

+0

@Adriano:如預期的那樣,正確的文件具有UTF-8,另一個ANSI。但爲什麼他們與相同的代碼不同? – LastElb 2012-03-13 18:20:35

回答

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文檔。 – 2015-10-01 15:13:18

0

您可以直接添加聲明

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