Remove encoding from XmlWriter

I use XmlWriter and XmlWriterSettings to write an XML file to disk. However, a system that parses an XML file complains about encoding.

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

He wants:

<?xml version="1.0" ?>

If I try OmitXmlDeclaration = true, then I don't get the xml string 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();
}
+4
source share
1 answer

Just stumbled upon this ---

  • delete completely XmlWriterSettings()and use the margin XmlTextWriter() Formattingto indent.
  • pass nullfor argumentEncoding XmlTextWriter ctor

The following code will create the result you are 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();

.Close()effectively creates a file - will also work approach usingand Create().

+3
source

Source: https://habr.com/ru/post/1545905/


All Articles