码迷,mamicode.com
首页 > 其他好文 > 详细

List转换成XML

时间:2016-06-26 06:55:56      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

 protected void Button1_Click(object sender, EventArgs e)
    {
        var customerlist = CustomerHelper.GetList();
        #region 方法一
        XmlDocument xd = new XmlDocument();
        using (StringWriter sw = new StringWriter())
        {
            XmlSerializer xz = new XmlSerializer(customerlist.GetType());
            xz.Serialize(sw, customerlist);
            //Response.Write(sw.ToString());
            xd.LoadXml(sw.ToString());
            Response.Write(xd.InnerXml);
        }

        #endregion

        #region 方法二
        string customerStr = Serializer(customerlist.GetType(), customerlist);
        Response.Write(customerStr);
        #endregion
    }

    /// <summary> 
    /// 序列化XML文件 
    /// </summary> 
    /// <param name="type">类型</param> 
    /// <param name="obj">对象</param> 
    /// <returns></returns> 
    public  string Serializer(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();
        return str;
    }

 

List转换成XML

标签:

原文地址:http://www.cnblogs.com/lijianhua/p/5617249.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!