0

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();
Kenney
  • 9,003
  • 15
  • 21
AnkitSablok
  • 3,021
  • 7
  • 35
  • 52
  • Do you know that there's no difference between specifying `encoding="utf-8"` and not? UTF-8 is the default encoding for XML. It only matters if you specify another encoding. – Kenney Dec 11 '15 at 22:43
  • the requirement is to get rid of that encoding="utf-8" string up in the xml header, cannot do much about that. I understand that there is no difference as the default is utf-8, the only thing is to replace that string with an empty string basically and I haven't been able to do that – AnkitSablok Dec 11 '15 at 22:45
  • I understand that the requirement is nonsense, is the only way to do that to read the entire xml file and do an text replacement? – AnkitSablok Dec 11 '15 at 22:48

2 Answers2

2

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.

Community
  • 1
  • 1
Kenney
  • 9,003
  • 15
  • 21
0

You can create a subclass of 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\"?>");
    }
}

Use it as such:

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

This will output <?xml version="1.0"?>. It will also support writing the document in any encoding, not tying you to UTF-8.

lenkan
  • 4,089
  • 1
  • 14
  • 12