日期:2014-05-18  浏览次数:21419 次

C#如何创建含有<?xml version="1.0" encoding="utf-8" ?>的声明
XmlDocument xml = new XmlDocument();
  XmlNode xmlnode;
  // xmlnode = xml.CreateNode(XmlNodeType.XmlDeclaration , "" , "");//创建头文件声明
  xmlnode = xml.CreateNode(XmlNodeType.XmlDeclaration , "" , "");
  xml.AppendChild(xmlnode);


  XmlElement x = xml.CreateElement("班级");
  xml.AppendChild(x);


  XmlElement subX2 = xml.CreateElement("第一小组");
  x.AppendChild(subX2);
  XmlElement subChild = xml.CreateElement("学号");
  subChild.InnerText = "108253040226";
  subX2.AppendChild(subChild);

  subChild = xml.CreateElement("姓名");
  subChild.InnerText = "甘全福";
  subX2.AppendChild(subChild);



  subChild = xml.CreateElement("学号");
  subChild.InnerText = "108253040227";
  subX2.AppendChild(subChild);
  subChild = xml.CreateElement("姓名");
  subChild.InnerText = "梁玉兰";
  subX2.AppendChild(subChild);



  subChild = xml.CreateElement("学号");
  subChild.InnerText = "108253040228";
  subX2.AppendChild(subChild);
  subChild = xml.CreateElement("姓名");
  subChild.InnerText = "黄海波";
  subX2.AppendChild(subChild);




  subX2 = xml.CreateElement("第二小组");
  x.AppendChild(subX2);
  subChild = xml.CreateElement("学号");
  subChild.InnerText = "108253040229";
  subX2.AppendChild(subChild);
  subChild = xml.CreateElement("姓名");
  subChild.InnerText = "张建";
  subX2.AppendChild(subChild);



  subChild = xml.CreateElement("学号");
  subChild.InnerText = "108253040230";
  subX2.AppendChild(subChild);
  subChild = xml.CreateElement("姓名");
  subChild.InnerText = "罗玉忠";
  subX2.AppendChild(subChild);



  subChild = xml.CreateElement("学号");
  subChild.InnerText = "108253040231";
  subX2.AppendChild(subChild);
  subChild = xml.CreateElement("姓名");
  subChild.InnerText = "张丽芳";
  subX2.AppendChild(subChild);



这样创建的XML文件是有声明的,但我想创建的是,在声明的部分添加属性encoding="utf-8"请各位大侠帮帮忙。

------解决方案--------------------
C# code

 using (MemoryStream _MemoryStream = new MemoryStream())
            {
                using (XmlTextWriter _XmlWriter = new XmlTextWriter(_MemoryStream, Encoding.UTF8))
                {
                    _XmlWriter.Formatting = Formatting.Indented;
                    _XmlWriter.WriteStartDocument();
                    
                }
                string a = System.Text.Encoding.UTF8.GetString(_MemoryStream.ToArray());
            }

------解决方案--------------------
XmlDocument.CreateXmlDeclaration 方法 
http://msdn.microsoft.com/zh-cn/library/system.xml.xmldocument.createxmldeclarati