要生成一个以下样式的xml文件 <?xml version="1.0" encoding="gb2312"?> <Root> <FirstColumn name="政治社会"> <SecondColumn Level="2" Code="0402000000" Father="政治社会">行政管理</SecondColumn> <SecondColumn Level="2" Code="0406000000" Father="政治社会">文化</SecondColumn> <SecondColumn Level="2" Code="0403000000" Father="政治社会">政治</SecondColumn> <SecondColumn Level="2" Code="0404000000" Father="政治社会">社会</SecondColumn> <SecondColumn Level="2" Code="0405000000" Father="政治社会">科技</SecondColumn> </FirstColumn> <FirstColumn name="宏观经济"> <SecondColumn Level="2" Code="0101000000" Father="宏观经济">区域经济</SecondColumn> <SecondColumn Level="2" Code="0102000000" Father="宏观经济">国有经济</SecondColumn> <SecondColumn Level="3" Code="0102010000" Father="国有经济">国有经济发展</SecondColumn> </FirstColumn> </Root> c#代码如下: 先在业务逻辑层创建一个类,用于获得数据库表中的信息,然后把该表的记录写进xml文件中 public void GenerateLinkXML() { XmlDocument xmldc = new XmlDocument(); XmlDeclaration xmldecl; xmldecl = xmldc.CreateXmlDeclaration("1.0", "gb2312", null); XmlElement xmle = xmldc.CreateElement("Root"); XmlElement root = xmldc.DocumentElement; xmldc.InsertBefore(xmldecl, root); GetLinkCategoryTable(); if (LinkCategoryTable.Rows.Count > 0) { for (int i = 0; i < LinkCategoryTable.Rows.Count; i++) { //创建根节点 xmldc.AppendChild(xmle); //创建子元素,一级栏目 XmlElement item = xmldc.CreateElement("Category"); item.SetAttribute("name", LinkCategoryTable.Rows[i]["CooperateComateCategoryName"].ToString().Trim()); //一级栏目的属性 xmle.AppendChild(item); //XmlElement secondColumn = xmldc.CreateElement("SecondColumn"); GetLinkNameTable(LinkCategoryTable.Rows[i]["CooperateComateCategoryName"].ToString().Trim()); //GetSonColumnData(System.Convert.ToInt32(this.dt.Rows[i]["Column_Level"].ToString().Trim()), this.dt.Rows[i]["MaskCode"].ToString().Trim()); if (this.LinkNameTable.Rows.Count > 0) { for (int j = 0; j < this.LinkNameTable.Rows.Count; j++) { XmlElement secondColumn = xmldc.CreateElement("List"); //secondColumn.SetAttribute("Level", this.SonColumn.Rows[j]["Column_Level"].ToString().Trim()); //secondColumn.SetAttribute("Code", this.SonColumn.Rows[j]["MaskCode"].ToString().Trim()); secondColumn.SetAttribute("CooperateComateName", this.LinkNameTable.Rows[j]["CooperateComateName"].ToString().Trim()); secondColumn.SetAttribute("CooperateComateURL", this.LinkNameTable.Rows[j]["CooperateComateURL"].ToString().Trim()); XmlText secondColumnName = xmldc.CreateTextNode(this.LinkNameTable.Rows[j]["CooperateComateName"].ToString().Trim()); secondColumn.AppendChild(secondColumnName); item.AppendChild(secondColumn); } } } xmldc.Save(this.xmlSavePath); } } 再在UI层,具体事件中加入如下代码,完成创建xml的过程 //生成xml文件 BusinessLogic.Homepage.CooperateComateXML createXML = new BusinessLogic.Homepage.CooperateComateXML(); createXML.XmlSavePath = Server.MapPath("../xml/CooperateComate.xml"); createXML.GenerateLinkXML();