0

I want to create an XML file to store information. I am using the following code. I would like to know how to specify the encoding for this file in code.

When I try to read this file in another form the characters in Japanese are distorted.

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);
ivcubr
  • 1,988
  • 9
  • 20
  • 28
Pradeep Singh
  • 23
  • 1
  • 6
  • 1
    can you try it ? http://stackoverflow.com/questions/157646/best-way-to-encode-text-data-for-xml – cat916 Aug 31 '12 at 04:07
  • Please show your XML reading code as it is likley where the problem is. There is nothing particularly wrong with code you shown (also you can safely cut all of the sample to 3-4 lines). – Alexei Levenkov Aug 31 '12 at 04:25

2 Answers2

3

You are using the overload of the Save method that takes a file name as a parameter. This method uses the UTF-8 encoding. Create an xml declaration before you create the root:

// ...

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

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

// ...

As a side note, if you want to have control over the encoding that the file is created with, you need to use one of the other overloads of the Save method.

Dan
  • 9,717
  • 4
  • 47
  • 65
-1

I changed my code to use the following and it works.

XmlDocument writer = new XmlDocument();
XmlDeclaration xmldecl;
xmldecl = writer.CreateXmlDeclaration("1.0", null, null);
xmldecl.Encoding = "UTF-8";
writer.AppendChild(xmldecl);
ivcubr
  • 1,988
  • 9
  • 20
  • 28
Pradeep Singh
  • 23
  • 1
  • 6