.NET XMLDocument Encoding issue

本文关键字:issue Encoding XMLDocument NET | 更新日期: 2023-09-27 18:27:44

我现在面临一个非常具体的问题。我将一些数据存储在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保存了文件,现在在保存并重新加载后,特殊字符(ä,ö,ü(出现异常.
实际上,在记事本中查看文件没有显示任何差异,但是在十六进制上查看有一些!这怎么可能?

.NET XMLDocument Encoding issue

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

/// <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");
可以直接

添加声明

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