Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove encoding from XmlWriter

Tags:

c#

xml

I'm using XmlWriter and XmlWriterSettings to write an XML file to disk. However, the system that is parsing the XML file is complaining about the encoding.

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

What it wants is this:

<?xml version="1.0" ?>

If I try OmitXmlDeclaration = true, then I don't get the xml line at all.

string destinationName = "C:\\temp\\file.xml";
string strClassification = "None";

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

using (XmlWriter writer = XmlWriter.Create(destinationName, settings))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("ChunkData");
    writer.WriteElementString("Classification", strClassification);
    writer.WriteEndElement();
}
like image 606
Pryach Avatar asked Jun 24 '14 21:06

Pryach


1 Answers

Just ran into this ---

  1. remove the XmlWriterSettings() altogether and use the XmlTextWriter()'s Formatting field for indention.
  2. pass in null for the Encoding argument of XmlTextWriter's ctor

The following code will create the output that you're looking for: <?xml version="1.0" ?>

var w = new XmlTextWriter(filename, null);
w.Formatting = Formatting.Indented; 
w.WriteStartDocument(); 
w.WriteStartElement("ChunkData");
w.WriteEndDocument(); 
w.Close();

The .Close() effectively creates the file - the using and Create() approach will also work.

like image 168
Bret Avatar answered Oct 04 '22 17:10

Bret