.NET XMLDocument编码问题

3

我现在面临一个非常具体的问题。 我正在将一些数据存储在XML文档中,并将其保存在硬盘上。 它们看起来像这样:

<?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()保存文件。 但是现在我从旧的电脑上保存了文件,现在在保存和重新加载后出现了特殊字符(ä、ö、ü)异常。
实际上,在记事本中查看文件没有任何差异,但在hex视图中有一些!这怎么可能?


2
如果您的问题非常具体,那么也许您可以编辑您的问题,使用更具体的标题?[so]上可能有10万个问题可以准确地使用“.NET XmlDocument”这个标题。 - John Saunders
5
检查文档编码(只需用 记事本 打开并执行 另存为,以查看它呈现的编码)。 - Adriano Repetti
@Adriano:正确的文件按预期采用UTF-8编码,另一个文件则采用ANSI编码。但是为什么在相同的代码下它们会不同呢? - LastElb
你可以在XML文件中写入encoding="utf-8",但是以ANSI格式编写,例如。我不知道它们为什么不同(可能取决于旧编辑器中使用的默认编码,但我猜测)。 - Adriano Repetti
也许这能对你有所帮助:https://dev59.com/U2855IYBdhLWcg3w7o-g - Lukinha RS
2个回答

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;
}

使用方法:

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

1
使用相同的代码,对于我来说 xmlDocument.InsertBerfore() 抛出了这个异常:无法将节点插入到指定位置。我的 XML 文件只是一个普通的 XML 文档。 - A-Sharabiani

0

你可以直接添加声明

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接