代码改变世界

List转换成XML

2016-06-26 02:59  lijianhua  阅读(1980)  评论(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;
    }