由于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文件保存的编码?

解决方案 »

  1.   

    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);
          
      }
    }
      

  2.   

    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();