Reset XML Declaration using XmlWriter

I am trying to use XmlWriter to create XML. I need to have the XML Declaration to be
<?xml version="1.0" encoding="ISO-8859-1"?>. I tried to set the Encoding in the XmlWriterSettings to "ISO-8859-1". I see the Encoding changes to “ISO-8859-1” in the setting but no matter what I do the resulting XML Declaration always looks like <?xml version="1.0" encoding="utf-16"?>. I don’t know if this is a bug or a feature.

Here is my code:

StringBuilder^ sbXml = gcnew StringBuilder();
XmlWriterSettings^ pXmlSettings = gcnew XmlWriterSettings();
XmlWriter^ w = nullptr;

pXmlSettings->Encoding = Encoding::GetEncoding( 1252 /*"ISO-8859-1"*/ );
pXmlSettings->OmitXmlDeclaration = false;
w = XmlWriter::Create( sbXml, pXmlSettings );
w->WriteStartDocument();
w->WriteStartElement( "root" );
w->WriteEndElement();
w->WriteEndDocument();

w->Flush();

Could anione please tell me how to cretae XML with a declaration of <?xml version="1.0" encoding="ISO-8859-1"?> using XmlWriter?

Thank you.

[1103 byte] By [Rafajna-Ujfalu] at [2008-2-13]
# 1
Probably, because you are using TextWriter-type-thing StringBuilder (not System.IO.Stream subclass) The XML Writer is using its encoding.

You can use MemoryStream and use byte array.

TheXMLMan at 2007-9-9 > top of Msdn Tech,.NET Development,XML and the .NET Framework...
# 2

Thanks for the idea. It works with MemoryStream. Here is the code, if someone is interested.

MemoryStream^ strmMm = gcnew MemoryStream();
XmlWriterSettings^ pXmlSettings = gcnew XmlWriterSettings();
XmlWriter^ w = nullptr;
pXmlSettings->Encoding = Encoding::GetEncoding( "ISO-8859-1" );
pXmlSettings->OmitXmlDeclaration = false;

w = XmlWriter::Create( strmMm, pXmlSettings );
w->WriteStartDocument();
w->WriteStartElement( "root" );
w->WriteEndElement();

w->WriteEndDocument();

w->Flush();

String^ s = Encoding::ASCII->GetString( strmMm->GetBuffer() );

Rafajna-Ujfalu at 2007-9-9 > top of Msdn Tech,.NET Development,XML and the .NET Framework...
# 3

The following solution will also work:-

XmlWriterSettings^ pXmlSettings = gcnew XmlWriterSettings();
XmlWriter^ w = nullptr;

pXmlSettings->Encoding = Encoding::GetEncoding( 1252 /*"ISO-8859-1"*/ );
pXmlSettings->OmitXmlDeclaration = false;
w = XmlWriter::Create( sbXml, pXmlSettings );

w->WriteProcessingInstruction( "xml", "version'=1.0' encoding='ISO-8859-1' ?>" );
w->WriteStartDocument();
w->WriteStartElement( "root" );
w->WriteEndElement();
w->WriteEndDocument();

w->Flush();

Hope it helps. I was also taken by surprise by XmlWriter's behaviour, see my post http://blogs.geekdojo.net/richardhsu/

Regards,
Richard Hsu.

richardhsu at 2007-9-9 > top of Msdn Tech,.NET Development,XML and the .NET Framework...

.NET Development

Site Classified