Xml帮助类
Posted 576
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Xml帮助类相关的知识,希望对你有一定的参考价值。
public class XMLHelper { #region 将xml文件转换为object对象类型 /// <summary> /// 将xml文件转换为object对象类型 /// </summary> /// <param name="path">xml文件的路径</param> /// <param name="type">要转换的类型的Type类型</param> /// <returns></returns> public static object ConvertXMLToObject(string path, Type type) { object obj = null; using (StreamReader reader = new StreamReader(path)) { string content = reader.ReadToEnd(); if (null == content) { throw new ArgumentNullException("xml"); } if (null == type) { throw new ArgumentNullException("type"); } XmlSerializer serializer = new XmlSerializer(type); StringReader strReader = new StringReader(content); XmlReader xreader = new XmlTextReader(strReader); try { obj = serializer.Deserialize(xreader); } catch(InvalidOperationException ie) { throw new InvalidOperationException("Can not convert xml to object", ie); } finally { xreader.Close(); } return obj; } } #endregion #region 将object对象转成xml保存 /// <summary> /// 将object对象转成xml保存 /// </summary> /// <param name="path">保存到xml文件的路径</param> /// <param name="obj">待转换的对象</param> /// <param name="toBeIndented">xml是否缩进 true:缩进,false:不缩进</param> public static void SaveObjectXML(string path, object obj, bool toBeIndented=true) { if (null == obj) { throw new ArgumentNullException("obj"); } UTF8Encoding encoding = new UTF8Encoding(false); XmlSerializer serializer = new XmlSerializer(obj.GetType()); MemoryStream stream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(stream, encoding); writer.Formatting = toBeIndented ? Formatting.Indented : Formatting.None; try { serializer.Serialize(writer, obj); } catch (InvalidOperationException ie) { throw new InvalidOperationException("Can not convert object to xml.", ie); } finally { writer.Close(); } string xml = encoding.GetString(stream.ToArray()); using (StreamWriter swriter = new StreamWriter(path)) { swriter.Write(xml); } } #endregion }
以上是关于Xml帮助类的主要内容,如果未能解决你的问题,请参考以下文章
android.view.InflateException:二进制 XML 文件第 15 行:二进制 XML 文件第 19 行:膨胀类片段时出错
在“设置”片段中夸大类PreferenceScreen的错误
当我切换到包含片段的活动时应用程序崩溃(二进制 XML 文件第 10 行:二进制 XML 文件第 10 行:膨胀类片段时出错)