创建xml文件时如何包含编码 [英] How to include encoding when creating xml files

查看:22
本文介绍了创建xml文件时如何包含编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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

// ...

附带说明,如果您想控制创建文件的编码,您需要使用 Save 方法.

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.

这篇关于创建xml文件时如何包含编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆