在XML序列化时去除默认命名空间xmlns:xsd和xmlns:xsi

来源:互联网 发布:d3.js 实现网络拓扑图 编辑:程序博客网 时间:2024/05/22 14:59

 

原文地址:在XML序列化时去除默认命名空间xmlns:xsd和xmlns:xsi作者:VanHelsing

可使用以下代码:

//Create our own namespaces for the outputXmlSerializerNamespaces ns = new XmlSerializerNamespaces (); //Add an empty namespace and empty valuens.Add ("", ""); //Create the serializerXmlSerializer slz = new XmlSerializer (someType); //Serialize the object with our own namespaces (notice the overload)slz.Serialize (myXmlTextWriter, someObject, ns);

此外,在评论中还提到了去除开头的<?xml version="1.0" encoding="utf-8"?>的方法:

XmlWriterSettings settings = new XmlWriterSettings (); // Remove the <?xml version="1.0" encoding="utf-8"?>settings.OmitXmlDeclaration = true; XmlWriter writer = XmlWriter.Create ("output_file_name.xml", settings); 另外,如果出现开头没有encoding="utf-8"时,应该使用: XmlWriterSettings settings = new XmlWriterSettings ();settings.Encoding = Encoding.UTF8; XmlWriter writer = XmlWriter.Create ("output_file_name.xml", settings);