XmlWriter writer = XmlWriter.Create("output.xml");
writer.WriteProcessingInstruction("xml", "version='1.0',
encoding='UTF-16'");
writer.WriteStartElement("root");
writer.Close();
If the default encoding is UTF-8, why does the XmlWriter by default emit
<?xml version="1.0" encoding="utf-16"?> if I don't explicitly specify that
processing instruction?
Any enlightenment greatly appreciated.
Zoe
> If the default encoding is UTF-8, why does the XmlWriter by default emit
> <?xml version="1.0" encoding="utf-16"?> if I don't explicitly specify that
> processing instruction?
It does not, the default encoding is UTF-8, at least when you create a
file (or write to a stream) e.g. with
using (XmlWriter xmlWriter = XmlWriter.Create(@"file.xml"))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("root");
xmlWriter.WriteElementString("foo", "bar");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
}
then the contents of the file written is
<?xml version="1.0" encoding="utf-8"?><root><foo>bar</foo></root>
The encoding UTF-16 is used when you use an XmlWriter over a
StringWriter as in
StringWriter stringWriter = new StringWriter();
using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("root");
xmlWriter.WriteElementString("foo", "bar");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
}
Console.WriteLine(stringWriter.ToString());
If you want to change that then use your own subclass of StringWriter e.g.
public class StringWriterWithEncoding : StringWriter {
private Encoding myEncoding;
public override Encoding Encoding {
get {
return myEncoding;
}
}
public StringWriterWithEncoding (Encoding encoding) : base() {
myEncoding = encoding;
}
}
then you can do
StringWriter stringWriter = new
StringWriterWithEncoding(Encoding.UTF8);
using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("root");
xmlWriter.WriteElementString("foo", "bar");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
}
Console.WriteLine(stringWriter.ToString());
--
Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Thanks for you quick response. It helped to make sense of the behavior I was
seeing.
Zoe
"Martin Honnen" <maho...@yahoo.de> wrote in message
news:%23UUXOe7...@TK2MSFTNGP03.phx.gbl...