How to include encoding when creating xml files

前端 未结 2 458
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-27 06:16

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 r

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-27 07:04

    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.

提交回复
热议问题