写XML

        public void Index()
        {
            //先创建XML,返回路径
            XmlDocument xmldoc = new XmlDocument();
            XmlDeclaration xmldecl;
            xmldecl = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null);
            xmldoc.AppendChild(xmldecl);

            //加入一个根元素
            XmlNode xmlelem = xmldoc.CreateElement("", "place", "");
            xmldoc.AppendChild(xmlelem);
            XmlNode root = xmldoc.SelectSingleNode("place");

            DataSet dsp = ServiceManager.UserBuyCarService.GetProvince();
            foreach (DataRow item in dsp.Tables[0].Rows)
            {
                XmlElement xe1 = xmldoc.CreateElement("Province");//创建:省 
                xe1.SetAttribute("code", item["provinceId"].ToString());
                xe1.SetAttribute("name", item["provinceName"].ToString());

                DataSet dscity = ServiceManager.UserBuyCarService.GetCity(item["provinceId"].ToString());
                foreach (DataRow city in dscity.Tables[0].Rows)
                {
                    XmlElement xcity = xmldoc.CreateElement("city");//创建:市
                    xcity.SetAttribute("code", city["cityId"].ToString());
                    xcity.SetAttribute("name", city["cityName"].ToString());
                    DataSet dscounty = ServiceManager.UserBuyCarService.GetCounty(city["cityId"].ToString());
                    foreach (DataRow county in dscounty.Tables[0].Rows)
                    {
                        XmlElement xcounty = xmldoc.CreateElement("area");//创建:区
                        xcounty.SetAttribute("code", county["countyId"].ToString());
                        xcounty.SetAttribute("name", county["countyName"].ToString());
                        xcity.AppendChild(xcounty);
                    }
                    xe1.AppendChild(xcity);
                }
                root.AppendChild(xe1);
            }

            //然后在保存到源位置
            xmldoc.AppendChild(xmlelem);
            //保存创建好的XML文档
            string m_strFilePath = "E:\\汽配2014.12.22" + @"\City2.xml";
            xmldoc.Save(m_strFilePath);
        }

 

posted @ 2015-04-15 13:41  aspnet_如月  阅读(168)  评论(0编辑  收藏  举报