【问题标题】:How to include encoding when creating xml files创建xml文件时如何包含编码
【发布时间】:2019-01-13 04:58:10
【问题描述】:

我想创建一个 XML 文件来存储信息。我正在使用以下代码。我想知道如何在代码中指定这个文件的编码。

当我尝试以另一种形式读取此文件时,日语中的字符会失真。

XmlDocument writer = new XmlDocument();
XmlElement root = writer.CreateElement("PatientFile");
writer.AppendChild(root);

XmlElement ID = writer.CreateElement("ID");
if (!string.IsNullOrEmpty(_a2Data.CurrentRecordId))
{
    ID.InnerText = _a2Data.CurrentRecordId;
}
root.AppendChild(ID);

XmlElement patientID = writer.CreateElement("PatientID");
if (!string.IsNullOrEmpty(_a2Data.PatId))
{
    patientID.InnerText = _a2Data.PatId;
}
root.AppendChild(patientID);

XmlElement patientName = writer.CreateElement("PatientName");
if (!string.IsNullOrEmpty(_a2Data.PatName))
{
    patientName.InnerText = _a2Data.PatName;
}
root.AppendChild(patientName);

XmlElement room = writer.CreateElement("Room");
if (!string.IsNullOrEmpty(_a2Data.RoomName))
{
    room.InnerText = _a2Data.RoomName;
}
root.AppendChild(room);
string folderName = ConfigurationManager.AppSettings["PatientXMLFiles"];
if (!Directory.Exists(folderName))
    Directory.CreateDirectory(folderName);

string fileName = ConfigurationManager.AppSettings["PatientXMLFiles"] + @"\" + _a2Data.CurrentRecordId + ".xml";
writer.Save(fileName);

【问题讨论】:

  • 请显示您的 XML 阅读代码,因为它很可能是问题所在。您显示的代码没有什么特别错误的(您也可以安全地将所有示例剪切为 3-4 行)。

标签: c# xml


【解决方案1】:

您正在使用将文件名作为参数的Save 方法的重载。此方法使用 UTF-8 编码。在创建根之前创建一个 xml 声明:

// ...

XmlDeclaration documentType = writer.CreateXmlDeclaration("1.0", "utf-8", null);
writer.AppendChild(documentType);

XmlElement root = writer.CreateElement("PatientFile");
writer.AppendChild(root);

// ...

附带说明,如果您想控制创建文件时使用的编码,则需要使用 Save 方法的其他重载之一。

【讨论】:

    【解决方案2】:

    我更改了我的代码以使用以下代码并且它可以工作。

    XmlDocument writer = new XmlDocument();
    XmlDeclaration xmldecl;
    xmldecl = writer.CreateXmlDeclaration("1.0", null, null);
    xmldecl.Encoding = "UTF-8";
    writer.AppendChild(xmldecl);
    

    【讨论】:

      猜你喜欢
      • 2010-09-13
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      相关资源
      最近更新 更多