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
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());
转自:http://www.eggheadcafe.com/software/aspnet/30335673/xmlwriter-encoding-and.aspx