linq to xml 中,有什么好的方法实现xml的字符编码吗?

我在XDeclaration中声明编码为gb2312,而在输出时却变成了utf-16。

var xdoc = new XDocument(
 
new XDeclaration("1.0", "gb2312", null),
 
new XElement("root", "")
);
StringBuilder sb = new StringBuilder();           
TextWriter tw = new StringWriter(sb); 
xdoc.Save(tw);      
Console.WriteLine(sb.ToString());
 输出:
<?xml version="1.0" encoding="utf-16"?>
<root></root>
我这知道原因了,是因为TextWriter的是使用的unicode字符集,而默认对应unicode字符集的编码为utf-16。

以上是我在博客园的提问,没有人给出答案,最后还是自己找到了答案。
Console.WriteLine(xDoc.Declaration.ToString()+ Environment.NewLine +xDoc.ToString());

完。

posted @ 2010-09-14 22:53  星晴  阅读(237)  评论(0编辑  收藏  举报