.NET XMLDocument编码问题

时间:2012-03-13 16:11:58

标签: c# .net vb.net xmldocument

我现在面临一个非常具体的问题。我将一些数据存储在XMLDocument中并将其保存在HDD上。它们看起来像这样:

<?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()保存它。 但是现在我从一台旧PC上保存了文件,现在我在保存和重新加载后对特殊字符(ä,ö,ü)有例外。
事实上,在记事本中查看文件显示没有差异,但在十六进制上查看有一些!这怎么可能?

2 个答案:

答案 0 :(得分: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");

答案 1 :(得分:0)

您可以直接添加声明

{{1}}