WriteStartDocument编写的XML编码标记错误

时间:2011-12-22 08:02:42

标签: c# xml vb.net

我已将XMLWriter设置为使用UTF8编码,但WriteStartDocument方法仍会写入UTF16标记。

这是代码的一部分:

            m_sbXML = New System.Text.StringBuilder

            m_xmlWriterSettings = New System.Xml.XmlWriterSettings
            With m_xmlWriterSettings
                .Indent = True
                .IndentChars = "    "
                .Encoding = System.Text.Encoding.UTF8
            End With

            m_xmlWriter = System.Xml.XmlWriter.Create(m_sbXML, m_xmlWriterSettings)

            Call m_xmlWriter.WriteStartDocument()

应该写下文档标签:

<?xml version="1.0" encoding="utf-8"?>

但它写道:

<?xml version="1.0" encoding="utf-16"?>

1 个答案:

答案 0 :(得分:3)

您正在写信StringBuilder。 .NET中的字符串始终采用UTF-16编码。

如果要创建UTF-8编码的XML文件,请写入Stream

示例:

var settings = new XmlWriterSettings
{
    Indent = True,
    IndentChars = "    ",
    Encoding = Encoding.UTF8
};

using (var stream = new MemoryStream())
using (var writer = XmlWriter.Create(stream, settings))
{
    writer.WriteStartDocument();
    // ...
}