如何在创建xml文件时包含编码

我想创建xmlfile来存储信息我正在使用以下代码,如何在此代码中指定编码,当我尝试以另一种forms读取此文件时,日语中的字符会被扭曲。

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

您正在使用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方法的其他重载之一。

我使用这些线,它现在工作

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