XML操作类

Posted 扶强

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了XML操作类相关的知识,希望对你有一定的参考价值。

public static class XmlHelper
{/// <summary>
    /// 将一个对象序列化为XML字符串
    /// </summary>
    /// <param name="o">要序列化的对象</param>
    /// <param name="encoding">编码方式</param>
    /// <returns>序列化产生的XML字符串</returns>
    public static string XmlSerialize(object o, Encoding encoding)
    {
        using( MemoryStream stream = new MemoryStream() ) {
            XmlSerializeInternal(stream, o, encoding);

            stream.Position = 0;
            using( StreamReader reader = new StreamReader(stream, encoding) ) {
                return reader.ReadToEnd();
            }
        }
    }

    /// <summary>
    /// 将一个对象按XML序列化的方式写入到一个文件
    /// </summary>
    /// <param name="o">要序列化的对象</param>
    /// <param name="path">保存文件路径</param>
    /// <param name="encoding">编码方式</param>
    public static void XmlSerializeToFile(object o, string path, Encoding encoding)
    {
        if( string.IsNullOrEmpty(path) )
            throw new ArgumentNullException("path");

        using( FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write) ) {
            XmlSerializeInternal(file, o, encoding);
        }
    }

    /// <summary>
    /// 从XML字符串中反序列化对象
    /// </summary>
    /// <typeparam name="T">结果对象类型</typeparam>
    /// <param name="s">包含对象的XML字符串</param>
    /// <param name="encoding">编码方式</param>
    /// <returns>反序列化得到的对象</returns>
    public static T XmlDeserialize<T>(string s, Encoding encoding)
    {
        if( string.IsNullOrEmpty(s) )
            throw new ArgumentNullException("s");
        if( encoding == null )
            throw new ArgumentNullException("encoding");

        XmlSerializer mySerializer = new XmlSerializer(typeof(T));
        using( MemoryStream ms = new MemoryStream(encoding.GetBytes(s)) ) {
            using( StreamReader sr = new StreamReader(ms, encoding) ) {
                return (T)mySerializer.Deserialize(sr);
            }
        }
    }

    /// <summary>
    /// 读入一个文件,并按XML的方式反序列化对象。
    /// </summary>
    /// <typeparam name="T">结果对象类型</typeparam>
    /// <param name="path">文件路径</param>
    /// <param name="encoding">编码方式</param>
    /// <returns>反序列化得到的对象</returns>
    public static T XmlDeserializeFromFile<T>(string path, Encoding encoding)
    {
        if( string.IsNullOrEmpty(path) )
            throw new ArgumentNullException("path");
        if( encoding == null )
            throw new ArgumentNullException("encoding");

        string xml = File.ReadAllText(path, encoding);
        return XmlDeserialize<T>(xml, encoding);
    }

//私有的
    private static void XmlSerializeInternal(Stream stream, object o, Encoding encoding)
    {
        if( o == null )
            throw new ArgumentNullException("o");
        if( encoding == null )
            throw new ArgumentNullException("encoding");

        XmlSerializer serializer = new XmlSerializer(o.GetType());

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.NewLineChars = "\\r\\n";
        settings.Encoding = encoding;
        settings.IndentChars = "    ";

        using( XmlWriter writer = XmlWriter.Create(stream, settings) ) {
            serializer.Serialize(writer, o);
            writer.Close();
        }
    }
}

 简洁版:

 #region  序列化

        /// <summary>
        /// XML序列化
        /// </summary>
        /// <param name="obj">序列对象</param>
        /// <param name="filePath">XML文件路径</param>
        /// <returns>是否成功</returns>
        public static bool SerializeToXml(object obj, string filePath)
        {
            bool result = false;

            FileStream fs = null;
            try
            {
                fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                serializer.Serialize(fs, obj);
                result = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
            return result;

        }

        /// <summary>
        /// XML反序列化
        /// </summary>
        /// <param name="type">目标类型(Type类型)</param>
        /// <param name="filePath">XML文件路径</param>
        /// <returns>序列对象</returns>
        public static object DeserializeFromXML(Type type, string filePath)
        {
            FileStream fs = null;
            try
            {
                fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                XmlSerializer serializer = new XmlSerializer(type);
                return serializer.Deserialize(fs);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
        }

        #endregion

 http://www.cnblogs.com/fish-li/archive/2011/12/18/2292037.html

以上是关于XML操作类的主要内容,如果未能解决你的问题,请参考以下文章

在Android中,如何将数据从类传递到相应的布局/片段文件?

当我切换到包含片段的活动时应用程序崩溃(二进制 XML 文件第 10 行:二进制 XML 文件第 10 行:膨胀类片段时出错)

在活动映射 xml 中膨胀类片段时出错

第 7 行的 InflateException 二进制 XML 文件:膨胀类片段时出错

二进制 XML 文件第 13 行:膨胀类片段时出错

如何从 Android Studio 中片段的 XML 布局导航到相应的 java 类?