.NET XMLDocument 编码问题

Las*_*Elb 3 .net c# 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>
Run Code Online (Sandbox Code Playgroud)

我正在通过 XMLDocument.Load() 加载文件并使用 XMLDocument.Save() 保存它。但是现在我从旧 PC 中保存了文件,现在在保存和重新加载后,特殊字符 (ä,ö,ü) 出现异常。
事实上,在记事本中查看文件没有任何区别,但在十六进制上查看有一些!这怎么可能?

Joh*_*son 6

您可以使用此扩展方法在保存之前设置解码。

/// <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;
}
Run Code Online (Sandbox Code Playgroud)

用法:

XmlDeclaration xmlDeclaration = xmlDocument.GetOrCreateXmlDeclaration();
xmlDeclaration.Encoding = Encoding.UTF8.WebName;
xmlDocument.Save(@"filename");
Run Code Online (Sandbox Code Playgroud)