如何使用 XmlTextWriter 将 xml header 中的 encoding=utf-8 替换为空字符串?

How to replace encoding=utf-8 in the xml header with an empty string using XmlTextWriter?

我在 C# 中使用 XmlTextWriter 从 CSV 生成 XML,结果 XML 我得到以下 header <xml version="1.0" encoding="utf-8">,问题是将此 encoding=utf-8 替换为空字符串,以便 header 变为 <xml version="1.0"?>。我已经搜索了很多,但到目前为止还没有找到任何东西。很想知道解决这个问题的方法。生成这个的一段代码如下-:

var writer = new XmlTextWriter(s, Encoding.UTF8) {
                    Formatting = Formatting.Indented
                };
writer.WriteStartDocument();

根据the docs有可能:

public XmlTextWriter(
  Stream w,
  Encoding encoding
)

encoding
Type: System.Text.Encoding

The encoding to generate. If encoding is null it writes out the stream as UTF-8 and omits the encoding attribute from the ProcessingInstruction.

您可以创建 XmlTextWriter 的子类:

public class XmlOmitEncodingWriter : XmlTextWriter
{
    public XmlOmitEncodingWriter(Stream w, Encoding encoding) : base(w, encoding)
    {}

    public XmlOmitEncodingWriter(string filename, Encoding encoding) : base(filename, encoding)
    {}

    public XmlOmitEncodingWriter(TextWriter w) : base(w)
    {}

    public override void WriteStartDocument()
    {
        WriteRaw("<?xml version=\"1.0\"?>");
    }
}

这样使用它:

var writer = new XmlOmitEncodingWriter(s, Encoding.UTF8) {
                Formatting = Formatting.Indented
            };
writer.WriteStartDocument();

这将输出 。它还将支持以任何编码编写文档,而不是将您绑定到 UTF-8。