XML 序列化与反序列化

实际中, 序列化实体到XML 比较多, 因为习惯存储过程接收XML参数, 然后解析到临时表, 再进行相应逻辑操作. 
序列化 本身不复杂, 主要实体定义及注解来完成名称转译等内容.
为了配合数据库接收xml. 增加了"/root"的层级.

public static class SerializerHelper
    {
        private static readonly String xmlFormat = "<?xml version=\"1.0\"?>\r\n<root>\r\n{0}\r\n</root>";

        public static T Deserializer<T>(String xml)
        {
            T obj = default(T);

            Byte[] bs = Encoding.Default.GetBytes(xml);
            using (MemoryStream ms = new MemoryStream(bs))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                obj = (T)serializer.Deserialize(ms);
            }

            return obj;
        }

        public static String Serializer<T>(T obj)
        {
            String xml = String.Empty;
            xml = SerializationService<T>(obj);

            return String.Format(xmlFormat, xml);
        }

        public static String Serializer<T>(IEnumerable<T> obj)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var ins in obj)
            {
                String xml = SerializationService<T>(ins);
                sb.AppendLine(xml);
            }

            return String.Format(xmlFormat, sb.ToString());
        }

        public static String Serializer<T1, T2>(IEnumerable<T1> obj1, IEnumerable<T2> obj2)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var item in obj1)
            {
                string xml = SerializationService<T1>(item);
                sb.AppendLine(xml);
            }

            foreach (var item in obj2)
            {
                string xml = SerializationService<T2>(item);
                sb.AppendLine(xml);
            }

            return String.Format(xmlFormat, sb.ToString());
        }

        private static string SerializationService<T>(T obj)
        {
            string xml = string.Empty;

            using (MemoryStream ms = new MemoryStream())
            {
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add(String.Empty, String.Empty);
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(ms, obj, ns);
                ms.Position = 0;
                StreamReader reader = new StreamReader(ms, Encoding.UTF8);
                reader.ReadLine();
                xml = reader.ReadToEnd();
                reader.Close();
            }

            return xml;
        }

        private static string SerializationService<T>(SerializerWrapper<T> obj)
        {
            string xml = string.Empty;

            using (MemoryStream ms = new MemoryStream())
            {
                XmlSerializer serializer = new XmlSerializer(typeof(SerializerWrapper<T>));
                serializer.Serialize(ms, obj);
                ms.Position = 0;
                StreamReader reader = new StreamReader(ms, Encoding.UTF8);
                xml = reader.ReadToEnd();
                reader.Close();
            }

            return xml;
        }
    }



反序列化; 
需要注意的是, 第一段采用StringReader 转换字符串到sr作为反序列化参数, 之后代码段使用流.

     //XML解析用
                A20ProductName ProductInfo = new A20ProductName();
                //解析XML
                using (StringReader sr = new StringReader(DictionaryXml))
                {
                    XmlSerializer xmldes = new XmlSerializer(typeof(A20ProductName));
                    ProductInfo = (A20ProductName)xmldes.Deserialize(sr);
                }


或者:
public static void xmlDeserialize()
{
    //xml来源可能是外部文件,也可能是从其他系统获得
    FileStream file = new FileStream(@"http://www.cnblogs.com/info.xml", FileMode.Open, FileAccess.Read);
    XmlSerializer xmlSearializer = new XmlSerializer(typeof(BaseInfo));
    BaseInfo info = (BaseInfo)xmlSearializer.Deserialize(file);
    file.Close();
    foreach (Person per in info.PerList)
    {
        Console.WriteLine("人员:");
        Console.WriteLine(" 姓名:" + per.Name);
        Console.WriteLine(" 年龄:" + per.Age);
        foreach (Books b1 in per.BookList)
        {
            foreach (Book b in b1.BookList)
            {
                Console.WriteLine(" 书:");
                Console.WriteLine("     ISBN:" + b.ISBN);
                Console.WriteLine("     书名:" + b.Title);
            }
        }
    }
}


var  revolvingFunds = default(DocumentElement);
            Byte[] bs = Encoding.Default.GetBytes(postResult);
            using (MemoryStream ms = new MemoryStream(bs))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(DocumentElement));
                revolvingFunds = (DocumentElement)serializer.Deserialize(ms);
            }

最后额外xml格式字符串 C#中使用:

           XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(XML);
                //查找<DataXML>
                XmlNode root = xmlDoc.SelectSingleNode("DataXML");
                string objectInstanceID = root["ObjectInstanceID"].InnerText; 
                string billID = root["BillID"].InnerText;
                string state = root["State"].InnerText;

参考优秀博客:
 https://www.cnblogs.com/hjianguo/p/5843079.html
https://www.cnblogs.com/sjqq/p/6933017.html

posted @ 2019-03-20 10:50  hijushen  阅读(166)  评论(0编辑  收藏  举报