一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

asp.net中Xml操作辅助类XmlUtil

时间:2022-06-25 03:49:56 编辑:袖梨 来源:一聚教程网

Xml操作辅助类主要包括两大操作,Xml的序列化与反序列化。代码如下:

 代码如下 复制代码


namespace Tmac.Utilities
{
    ///


    /// Xml操作类
    ///

    public class XmlUtil
    {
        ///
        /// 序列化对象为xml(或字节流)
        ///

        ///
        ///
        public static string XmlSerialize(object obj)
        {
            string result = null;

            try
            {
                XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
                using (MemoryStream stream = new MemoryStream())
                {
                    XmlTextWriter xmlTextWriter = new XmlTextWriter(stream, new UTF8Encoding(false));
                    xmlTextWriter.Formatting = Formatting.Indented;
                    xmlSerializer.Serialize(xmlTextWriter, obj);
                    xmlTextWriter.Flush();
                    xmlTextWriter.Close();
                    UTF8Encoding uTF8Encoding = new UTF8Encoding(false, true);
                    result = uTF8Encoding.GetString(stream.ToArray());
                }

            }
            catch (Exception ex)
            {
                throw new Exception("Couldn't serialize object:"+obj.GetType().Name,ex);
            }
            return result;
        }

        ///


        /// 反序列xml为对象
        ///

        ///
        ///
        ///
        ///
        public static T XmlDeserialize(Type type,string xmlPath)
        {
            T obj=default(T);

            XmlSerializer xmlSerializer = new XmlSerializer(type);
            try
            {
                using (StreamReader sr = new StreamReader(xmlPath))
                {
                    obj=(T)xmlSerializer.Deserialize(sr);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format("Couldn't parse xml:{0};Type:{1}",xmlPath,type.FullName), ex);
            }
            return obj;
        }
    }
}

热门栏目