How can I force XDocument to output “UTF-8” in the declaration line?

前端 未结 3 1821
误落风尘
误落风尘 2020-12-20 13:46

The following code produces this output:



  
    

        
3条回答
  •  误落风尘
    2020-12-20 14:40

    This is not a bug in .NET. This is due to you using StringWriter as the target for your XDocument. Since StringWriter internally uses UTF-16, the document must also use UTF-16 as encoding. If you save the XDoc to a stream or a file, it will use UTF-8 as instructed.

    For more information, see MSDN information about StringWriter.Encoding:

    This property is necessary for some XML scenarios where a header must be written containing the encoding used by the StringWriter. This allows the XML code to consume an arbitrary StringWriter and generate the correct XML header.

提交回复
热议问题