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

前端 未结 3 1798
误落风尘
误落风尘 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.

    0 讨论(0)
  • 2020-12-20 14:44

    Allow me answer my own question, this seems to work:

    private static string BuildXmlWithLINQ()
    {
        XDocument xdoc = new XDocument
        (
            new XDeclaration("1.0", "utf-8", "yes"),
            new XElement("customers",
                new XElement("customer",
                    new XElement("firstName", "Jim"),
                    new XElement("lastName", "Smith")
                )
            )
        );
        return xdoc.Declaration.ToString() + Environment.NewLine + xdoc.ToString();
    }
    
    0 讨论(0)
  • 2020-12-20 14:49

    You can use the following code as an example

    XDocument doc = GetXmlDoc();
    using (var stream = new MemoryStream())
    {
        doc.Save(stream, SaveOptions.DisableFormatting);
        var docBytes = stream.ToArray();
        File.WriteAllBytes("fileName.xml", docBytes);
    }
    
    0 讨论(0)
提交回复
热议问题