private string GetDepartmentInfoXML(string DepartmentId)
 {               
   Department d = CommonSrv.LoadObjectById(typeof(Department), DepartmentId) as Department;   XmlNode node = null;
   XmlDocument xmlDoc = new XmlDocument();
   XmlNode rootNode = xmlDoc.CreateNode(XmlNodeType.Element, "Department", "");
   xmlDoc.AppendChild(rootNode);   node = xmlDoc.CreateNode(XmlNodeType.Element, "Succeed", "");
   node.InnerText = "1";
   rootNode.AppendChild(node);   node = xmlDoc.CreateNode(XmlNodeType.Element, "Name", "");
   node.InnerText = d.Name;
   rootNode.AppendChild(node);   node = xmlDoc.CreateNode(XmlNodeType.Element, "Re", "");
   node.InnerText = d.Re;
   rootNode.AppendChild(node);
        return xmlDoc.OuterXml;
    }
通过读取数据库中的数据生成XML文件,没有中文时运行正确,但是当数据d.Name或d.Re中有中文时就会出错,请问如何解决?是不是由于编码的问题呀,动态创建XML如何设置编码?

解决方案 »

  1.   

    XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "gb2312", "yes");
    doc.AppendChild(dec);
      

  2.   

    hdt:我加上XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "gb2312", "yes"); 
    doc.AppendChild(dec);以后中文显示成乱码了呀?
      

  3.   

    doc.CreateXmlDeclaration("1.0", "gb2312", "yes");
      

  4.   

    XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", "yes"); 
    doc.AppendChild(dec);不用中文运行正常,使用中文就报错,通过这种描述可以确认就是编码问题,你使用utf-8编码试试看。
      

  5.   

    输出xml的时候选择utf-8的编码
      

  6.   

    XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", "yes"); 
    可能就是编码的问题