public bool SaveXML(DataTable dt)
        {
            try
            {

                string filePath ="111.xml";
                XmlOperate xmlop = new XmlOperate();
                //加载xml文件,用于保存数据
                XmlDocument xmlDoc = xmlop.LoadXml(filePath, "Root");
                foreach (DataRow row in dt.Rows)
                {
                    dsModel rdsModel = new dsModel();
                    rdrsModel.name= row["姓名"].ToString();
                    rdrsModel.age= row["年龄"].ToString();
                    rdrsModel.sex= row["性别"].ToString();


                    //保存新纪录到XML文件
                    xmlop.AddXmlElement<RdRecordsModel>(filePath, xmlDoc, "Root", rdsModel);
                }

                return true;
            }
            catch (Exception ex)
            {
                throw new ApplicationException("保存数据到文件失败!原因:" + ex.Message);
            }
        }

 

 

    /// <summary>
        /// 添加XML节点
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="filePath">文件路径</param>
        /// <param name="xmlDoc">XmlDocument对象</param>
        /// <param name="root_node">根节点</param>
        /// <param name="t">对象</param>
        public void AddXmlElement<T>(string filePath,XmlDocument xmlDoc,string root_node,T t)
            where T : new()
        {
            XmlNode xmlDocSelect = xmlDoc.SelectSingleNode(root_node);
            XmlElement xmlEle = xmlDoc.CreateElement(t.GetType().Name);
            //获取对象属性
            PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            //遍历对象的属性,并获取属性的值
            foreach (PropertyInfo item in properties)
            {
                string attName = item.Name;
                object value = item.GetValue(t,null);
                if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
                {
                    XmlAttribute xmlattr = xmlDoc.CreateAttribute(attName);
                    xmlattr.Value = value.ToString();
                    xmlEle.Attributes.Append(xmlattr);
                }
            }
            xmlDocSelect.AppendChild(xmlEle);
            xmlDoc.Save(filePath);
        }

posted on 2012-11-07 11:50  清风暮雨  阅读(151)  评论(0)    收藏  举报