Pryach
Pryach

Reputation: 417

Remove encoding from XmlWriter

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

Upvotes: 6

Views: 7579

Answers (1)

Bret
Bret

Reputation: 2291

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.

Upvotes: 6

Related Questions