How to include encoding when creating xml files

前端 未结 2 424
爱一瞬间的悲伤
爱一瞬间的悲伤 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 06:59

    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);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题