XML反序列化实体类

前端之家收集整理的这篇文章主要介绍了XML反序列化实体类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我们的生活有太多无奈,我们无法改变,也无力去改变,更糟的是,我们失去了改变的想法。


实体类

BaseInfo.cs

public class BaseInfo
    {
        List<Person> perList = new List<Person>();

        [XmlElement(ElementName = "Person")]
        public List<Person> PerList
        {
            get { return perList; }
            set { perList = value; }
        }
    }

Book.cs

public class Book
    {
        string isbn;
        string title;

        public Book() { }

        public Book(string isbn,string title)
        {
            this.isbn = isbn;
            this.title = title;
        }

        public string ISBN
        {
            get { return isbn; }
            set { isbn = value; }
        }

        public string Title
        {
            get { return title; }
            set { title = value; }
        }
    }

Books.cs

public class Books
    {
        List<Book> bookList = new List<Book>();

        [XmlElement(ElementName = "Book")]
        public List<Book> BookList
        {
            get { return bookList; }
            set { bookList = value; }
        }
    }

Person.cs

public class Person
    {
        string name;
        int age;
        List<Books> bookList = new List<Books>();

        /// <summary>
        /// 必须有默认的构造函数
        /// </summary>
        public Person()
        { }

        public Person(string name,int age)
        {
            this.name = name;
            this.age = age;
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public int Age
        {
            get { return age; }
            set { age = value; }
        }

        [XmlElement(ElementName = "Books")]
        public List<Books> BookList
        {
            get { return bookList; }
            set { bookList = value; }
        }
    }

Game.cs和Order.cs

public class Game
    {
        [XmlElement("no")]
        public string No { get; set; }
        [XmlElement("pwd")]
        public string Pwd { get; set; }
        [XmlElement("extime")]
        public string Extime { get; set; }
    }


    [XmlRoot("order")]
    public class Order
    {
        [XmlElement("id")]
        public string Id { get; set; }
        [XmlElement("cid")]
        public string Cid { get; set; }
        [XmlElement("cnum")]
        public string Cnum { get; set; }
        [XmlElement("cash")]
        public string Cash { get; set; }
        [XmlElement("name")]
        public string Name { get; set; }

        [XmlArray("games")]
        [XmlArrayItem("game")]
        public List<Game> GameList { get; set; }
    }

XmlUtils.cs

public class XmlUtil
    {
        #region 反序列化

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="xml">XML字符串</param>
        /// <returns></returns>
        public static object Deserialize(Type type,string xml)
        {
            try
            {
                using (var sr = new StringReader(xml))
                {
                    var xmldes = new XmlSerializer(type);

                    return xmldes.Deserialize(sr);
                }
            }

            catch (Exception e)
            {
                return null;
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type"></param>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static object Deserialize(Type type,Stream stream)
        {
            var xmldes = new XmlSerializer(type);

            return xmldes.Deserialize(stream);
        }

        #endregion

        #region 序列化XML文件

        /// <summary>
        /// 序列化XML文件
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string Serializer(Type type,object obj)
        {
            var Stream = new MemoryStream();

            //创建序列化对象 

            var xml = new XmlSerializer(type);

            try
            {
                //序列化对象 

                xml.Serialize(Stream,obj);
            }

            catch (InvalidOperationException)
            {
                throw;
            }

            Stream.Position = 0;

            var sr = new StreamReader(Stream);

            string str = sr.ReadToEnd();

            return str;
        }

        #endregion

        #region 将XML转换为DATATABLE

        /// <summary>
        /// 将XML转换为DATATABLE
        /// </summary>
        /// <param name="FileURL"></param>
        /// <returns></returns>
        public static DataTable XmlAnalysisArray()
        {
            try
            {
                string FileURL = ConfigurationManager.AppSettings["Client"];

                var ds = new DataSet();

                ds.ReadXml(FileURL);

                return ds.Tables[0];
            }

            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);

                return null;
            }
        }

        /// <summary>
        /// 将XML转换为DATATABLE
        /// </summary>
        /// <param name="FileURL"></param>
        /// <returns></returns>
        public static DataTable XmlAnalysisArray(string FileURL)
        {
            try
            {
                var ds = new DataSet();

                ds.ReadXml(FileURL);

                return ds.Tables[0];
            }

            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);

                return null;
            }
        }

        #endregion

        #region 获取对应XML节点的值

        /// <summary>
        /// 摘要:获取对应XML节点的值
        /// </summary>
        /// <param name="stringRoot">XML节点的标记</param>
        /// <returns>返回获取对应XML节点的值</returns>
        public static string XmlAnalysis(string stringRoot,string xml)
        {
            if (stringRoot.Equals("") == false)
            {
                try
                {
                    var XmlLoad = new XmlDocument();

                    XmlLoad.LoadXml(xml);

                    return XmlLoad.DocumentElement.SelectSingleNode(stringRoot).InnerXml.Trim();
                }

                catch (Exception ex)
                {
                }
            }

            return "";
        }

        #endregion
    }

Index.aspx内容:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:Button ID="btnParse" runat="server" Text="XML反序列化一" onclick="btnParse_Click" />

        <asp:Button ID="btnTwoParse" runat="server" Text="XML反序列化二" onclick="btnTwoParse_Click" />

    </div>
    </form>
</body>
</html>

Index.aspx.cs代码:

public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender,EventArgs e)
        {


        }

        protected void btnParse_Click(object sender,EventArgs e)
        {
            string xmlStr = @"<order>
                                  <id>1990000000</id>
                                  <cid>11111111</cid>
                                  <cnum>2</cnum>
                                  <cash>20</cash>
                                  <name>生化危机</name>
                                  <games>
                                     <game>
                                       <no>21000000</no>
                                       <pwd>123456</pwd>
                                       <extime>2020-01-23</extime>
                                     </game>
                                     <game>
                                       <no>21000001</no>
                                       <pwd>234567</pwd>
                                       <extime>2020-01-23</extime>
                                     </game>
                                  </games>
                            </order> ";

            Order order = (Order)XmlUtil.Deserialize(typeof(Order),xmlStr);
            Response.Write("ID="+order.Id+"<br/>"+
                "name="+order.Name+"<br/>"+
                "game一的no="+order.GameList[0].No+"<br/>"+
                "game一的pwd=" + order.GameList[0].Pwd + "<br/>" +
                "game二的no=" + order.GameList[1].No + "<br/>" +
                "game二的pwd=" + order.GameList[1].Pwd + "<br/>"
                );
        }

        protected void btnTwoParse_Click(object sender,EventArgs e)
        {
            string xmlStr = @"<BaseInfo>
                              <Person>
                                <Name>小明</Name>
                                <Age>16</Age>
                                <Books>
                                  <Book>
                                    <ISBN>123</ISBN>
                                    <Title>借的书1</Title>
                                  </Book>
                                </Books>
                              </Person>
                              <Person>
                                <Name>小红</Name>
                                <Age>18</Age>
                                <Books>
                                  <Book>
                                    <ISBN>456</ISBN>
                                    <Title>借的书2</Title>
                                  </Book>
                                  <Book>
                                    <ISBN>789</ISBN>
                                    <Title>借的书3</Title>
                                  </Book>
                                </Books>
                              </Person>
                            </BaseInfo>";


            XmlSerializer xmlSearializer = new XmlSerializer(typeof(BaseInfo));
            StringReader sr = new StringReader(xmlStr);
            BaseInfo info = (BaseInfo)xmlSearializer.Deserialize(sr);
            foreach (Person per in info.PerList)
            {
                Response.Write("人员:");
                Response.Write(" 姓名:" + per.Name+"<br />");
                Response.Write(" 年龄:" + per.Age + "<br />");
                foreach (Books b1 in per.BookList)
                {
                    foreach (Book b in b1.BookList)
                    {
                        Response.Write(" 书:");
                        Response.Write("     ISBN:" + b.ISBN + "<br />");
                        Response.Write("     书名:" + b.Title + "<br />");
                    }
                }
                Response.Write("<hr />");
            }
        }
    }

运行结果如图:


原文链接:https://www.f2er.com/xml/294390.html

猜你在找的XML相关文章