/// <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); } }