XML序列化
Posted 雨悟极
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了XML序列化相关的知识,希望对你有一定的参考价值。
/// <summary> /// 将指定路径XML文件序列化为指定对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="path">文件路径</param> /// <param name="obj">需要序列化的对象</param> /// <param name="isOmitXmlDeclaration">true:省略XML声明;否则为false.默认false,即编写 XML 声明。</param> /// <param name="removeDefaultNamespace">是否移除默认名称空间(如果对象定义时指定了:XmlRoot(Namespace = "http://www.xxx.com/xsd")则需要传false值进来)</param> public static void XmlSerialize<T>(string path, T obj, bool isOmitXmlDeclaration = false, bool removeDefaultNamespace = true) { XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = isOmitXmlDeclaration; settings.Encoding = Encoding.UTF8; settings.Indent = true; settings.IndentChars = "\t"; settings.NewLineOnAttributes = true; settings.NewLineChars = "\r\n"; using (XmlWriter xmlwriter = XmlWriter.Create(path, settings)) { XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces(); if (removeDefaultNamespace) { xmlns.Add(string.Empty, string.Empty); //在XML序列化时去除默认命名空间xmlns:xsd和xmlns:xsi } XmlSerializer ser = new XmlSerializer(typeof(T)); ser.Serialize(xmlwriter, obj, xmlns); } }
以上是关于XML序列化的主要内容,如果未能解决你的问题,请参考以下文章