Home > Software engineering >  Change StringWriter xml node output
Change StringWriter xml node output

Time:05-20

I am using .NET Core 3.1

Is there any way of editing the xml node that StringWriter outputs?

I'd like to change the casing of "utf-8" for example. The output currently looks like below.

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

My code is like below.

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

My function that writes out xml


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

CodePudding user response:

You can write the Xml declaration manually:

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();
}
  • Related