Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change StringWriter xml node output

Tags:

c#

xml

.net-core

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();
}
like image 623
JessicaM Avatar asked May 16 '26 06:05

JessicaM


1 Answers

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();
}
like image 170
Markus Avatar answered May 18 '26 20:05

Markus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!