zoukankan      html  css  js  c++  java
  • C# Asp.net中xml串与对象互相转换

    public class XmlUtil
        {
            #region 反序列化
            /// <summary>
            /// 将XML字符串反序列化为对象
            /// </summary>
            /// <param name="type">类型</param>
            /// <param name="xml">XML字符串</param>
            /// <returns></returns>
            public static object Xml2Obj(Type type, string xml)
            {
                try
                {
                    using (StringReader sr = new StringReader(xml))
                    {
                        XmlSerializer xmldes = new XmlSerializer(type);
                        return xmldes.Deserialize(sr);
                    }
                }
                catch (Exception e)
                {
    
                    return null;
                }
            }
            #endregion
    
            #region 对象转化成
            /// <summary>
            /// 对象转化成XML
            /// </summary>
            /// <param name="type">类型</param>
            /// <param name="obj">对象</param>
            /// <returns></returns>
            public static string Obj2Xml(Type type, object obj)
            {
                MemoryStream Stream = new MemoryStream();
                XmlSerializer xml = new XmlSerializer(type);
                try
                {
                    //序列化对象
                    xml.Serialize(Stream, obj);
                }
                catch (InvalidOperationException)
                {
                    throw;
                }
                Stream.Position = 0;
                StreamReader sr = new StreamReader(Stream);
                string str = sr.ReadToEnd();
    
                sr.Dispose();
                Stream.Dispose();
    
                return str;
            }
    
            #endregion
        }

    对象类:

     [XmlRoot("people")]
        public class People
        {
            public string name { get; set; }
            public string age { get; set; }
        } 
     
    xml串:
    <people>
    <name>LiMing</name>
    <age>25</age>
    </people>
     
    var people = (People)XmlUtil.Xml2Obj(typeof(People), xmlStr);
  • 相关阅读:
    Asp.NET调用有道翻译API
    JSON C# Class Generator ---由json字符串生成C#实体类的工具
    让jQuery的contains方法不区分大小写
    javascript parseUrl函数(来自国外的获取网址url参数)
    typescript
    webpack 第二部分
    express node 框架介绍
    webpack 最新版
    es6 字符串 对象 拓展 及 less 的语法
    es6 的数组的方法
  • 原文地址:https://www.cnblogs.com/qk2014/p/7658347.html
Copyright © 2011-2022 走看看