c# - WriteStartDocument 编写的错误 XML 编码标记

标签 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"?>

最佳答案

您正在写信给 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();
    // ...
}

关于c# - WriteStartDocument 编写的错误 XML 编码标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8600936/

相关文章:

vb.net - 如何从 VB.NET 运行 DOS/CMD/命令提示符命令?

c# - Web Api HTTPPost 不接受 int

c# - ASP.NET - 从数据库中检索图像列表并将它们显示在 View 中?

c# - LINQ 值查询返回错误的字符串

c# - 使用 Schematron 验证 XML

c# - SecurityElement.IsValidText 在 "&"上返回 true ... 为什么?

c# - 如何在 EditorFor 中访问 C# 模型属性

c# - 为什么此对象相等性测试失败?

.net - 在 Invoke() 内部运行时,跨线程操作对表单控件无效 - .NET

c# - WPF Metro UI 图表 - 负值