C#:如何指定XML文件保存的编码?

Qiaorui 2006-11-28 11:31:17
由于XML很小,偶用XmlDocument来生成
XmlDocument xmldoc = new XmlDocument();
XmlNode nodePI = xmldoc.CreateProcessingInstruction("xml","version=\"1.0\" encoding=\"gb2312\"");
...//生成XML节点
xmldoc.Save("test.xml");

在代码中,XML的文档的encoding指定为gb2312,但保存XML文件时,文件的编码却是UTF-8,二者完全不同,如果XML含有中文,就不行了。怎样指定XML文件保存的编码?
...全文
571 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
PP77454370 2006-11-30
  • 打赏
  • 举报
回复
经典
Alldim 2006-11-28
  • 打赏
  • 举报
回复
FileStream fs=new FileStream(Server.MapPath("test.xml"),FileMode.Create);
XmlTextWriter xtr=new XmlTextWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
xtr.Formatting=Formatting.Indented;
xtr.Indentation=0;
xtr.WriteStartDocument();
ds.WriteXml(xtr);
xtr.Close();
fs.Close();
qingbt 2006-11-28
  • 打赏
  • 举报
回复
直接用encoding="UTF-8"不行吗?
flyskywlh 2006-11-28
  • 打赏
  • 举报
回复
using System;
using System.IO;
using System.Xml;

public class Sample {

public static void Main() {

// Create and load the XML document.
XmlDocument doc = new XmlDocument();
string xmlString = "<book><title>Oberon's Legacy</title></book>";
doc.Load(new StringReader(xmlString));

// Create an XML declaration.
XmlDeclaration xmldecl;
xmldecl = doc.CreateXmlDeclaration("1.0",null,null);
xmldecl.Encoding="UTF-8";
xmldecl.Standalone="yes";

// Add the new node to the document.
XmlElement root = doc.DocumentElement;
doc.InsertBefore(xmldecl, root);

// Display the modified XML document
Console.WriteLine(doc.OuterXml);

}
}

smartstar2005 2006-11-28
  • 打赏
  • 举报
回复
Mark

110,532

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧