"景先生毕设|www.jxszl.com

List转XML C#代码样例

2023-12-15 14:03编辑: www.jxszl.com景先生毕设
List转XML C#代码样例

        #region  List转XML C#代码样例

        /// <summary>
        /// ListToXML
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="root"></param>
        /// <param name="child"></param>
        /// <returns></returns>
        public static string ListToXml<T>(List<T> list, string root, string child)
        {
            //创建XML文档  
            XDocument bookDoc = new XDocument();
            //创建声明对象  
            //XDeclaration xDeclaration = new XDeclaration("1.0", "utf-8", "yes");
            //bookDoc.Declaration = xDeclaration;    //指定XML声明对象  
            //创建bookstore节点  
            XElement xElement = new XElement(root);
            //List<T> list = new List<T>();
            T t = default(T);
            PropertyInfo[] propertypes = null;
            string tempName = string.Empty;
            t = Activator.CreateInstance<T>();
            propertypes = t.GetType().GetProperties();
            for (int i = 0; i < list.Count; i++)
            {

                XElement bookXml = new XElement(child);
                foreach (PropertyInfo pro in propertypes)
                {
                    //添加子节点  
                    T tt = list[i];
                    string ta = string.Empty;
                    try
                    {
                        ta = pro.GetValue(tt, null).ToString();
                    }
                    catch
                    {

                    }
                    if (pro.Name == "DOEVENT")
                    {
                        bookXml.Add(new XElement(pro.Name, ta));
                    }
                    bookXml.Add(new XElement(pro.Name, ta));

                }
                xElement.Add(bookXml);
            }
            return xElement.ToString();
        }

        #endregion


原文链接:http://www.jxszl.com/biancheng/C/556431.html