更改 StringWriter xml 节点输出

Change StringWriter xml node output

我正在使用 .NET Core 3.1

有什么方法可以编辑 StringWriter 输出的 xml 节点吗?

例如,我想更改“utf-8”的大小写。当前的输出如下所示。

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

我的代码如下。

public class MyStringWriter: StringWriter
{
    public override Encoding Encoding => Encoding.UTF8;
}

我写出的函数xml


using (TextWriter tw= new MyStringWriter())
{
    using (var xw = XmlWriter.Create(tw))
    {
        xmlDoc.WriteTo(xw);
    }
    var output = tw.ToString();
}

您可以手动编写 Xml 声明:

using (TextWriter tw= new MyStringWriter())
{
    using (var xw = XmlWriter.Create(tw))
    {
        xw.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
        xmlDoc.WriteTo(xw);
    }
    var output = tw.ToString();
}