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); 
2
  • 1
    can you try it ? stackoverflow.com/questions/157646/… Commented Aug 31, 2012 at 4: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). Commented Aug 31, 2012 at 4:25

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.