将XML序列化成对象

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

1

namespace MvcAppTest.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {

            string sql = "select a.*,(select UserName,Password,Error from T_UserLogin  where LoginId=a.LoginId  for xml auto,type,elements) as UserInfoXML from T_UserInfo a ";

            List<T_UserInfo> list = sqlHelper.ExecuteClass<T_UserInfo>(sql,null);

            //经过sql语句查询后UserInfoXML字段的值为:
            //  <T_UserLogin><UserName>无盐海</UserName><Password>123456</Password><Error>1</Error></T_UserLogin>

            //将XML格式的字符串转换成对象(特别要注意<T_UserLogin>要与目标类名称一致)
            var objList = HomeController.XMLToObject<T_UserLogin>(list.First().UserInfoXML,Encoding.UTF8);
            var name = objList.UserName;
            return View();
        }


        /// <summary>
        /// 将object对象序列化成XML
        /// </summary>
        /// <typeparam name="T">需要序列化的对象</typeparam>
        /// <param name="encoding">如果序列化出错,可以尝试修改下encoding的值试试</param>
        /// <returns></returns>
        public static string ObjectToXML<T>(T t,Encoding encoding)
        {
            XmlSerializer ser = new XmlSerializer(t.GetType());
            using (MemoryStream mem = new MemoryStream())
            {
                using (XmlTextWriter writer = new XmlTextWriter(mem,encoding))
                {
                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                    ns.Add("","");
                    ser.Serialize(writer,t,ns);
                    return encoding.GetString(mem.ToArray()).Trim();
                }
            }
        }

        /// <summary>
        /// 将XML反序列化成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">需要序列化的XML字符串</param>
        /// <param name="encoding">如果序列化出错,可以尝试修改下encoding的值试试</param>
        /// <returns></returns>
        public static T XMLToObject<T>(string source,Encoding encoding)
        {
            XmlSerializer mySerializer = new XmlSerializer(typeof(T));
            using (MemoryStream stream = new MemoryStream(encoding.GetBytes(source)))
            {
                return (T)mySerializer.Deserialize(stream);
            }
        }
    }
}
namespace MvcAppTest.DAL
{
    [Serializable]
    public class T_UserInfo
    {
        public int Id { get; set; }

        public string UserName { get; set; }

        public int Age { get; set; }

        public string UserInfoXML { get; set; }
    }
    [Serializable]
    public class T_UserLogin
    {
        public string UserName { get; set; }

        public string Password { get; set; }

        public int Error { get; set; }
    }
}
原文链接:https://www.f2er.com/xml/295018.html

猜你在找的XML相关文章