Search code examples
c#.netxmlxmltextwriter

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


I am using XmlTextWriter in C# to generate XML's from CSV's and in the result XML I am getting the following header <xml version="1.0" encoding="utf-8"> and the problem is to replace this encoding=utf-8 with an empty string so that the header becomes <xml version="1.0"?>. I have searched a lot and have not been able to find anything as of now. Would love to know solutions to combat this problem. The piece of code that generates this is as follows -:

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

Solution

  • According to the docs it is possible:

    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.