首页  :: 新随笔  :: 订阅 订阅  :: 管理

有关XmlWriter中XML的encoding问题~

Posted on 2008-12-22 16:20  礼拜一  阅读(2083)  评论(1编辑  收藏  举报

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