去掉XML命名空间及声明头不影响反序列化,
直接上代码:
// 序列化这个对象 int obj = 1; XmlSerializer serializer = new XmlSerializer(obj.GetType()); // 将对象序列化输出到文件 FileStream stream = new FileStream("hh.xml", FileMode.Create); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = " "; settings.NewLineChars = "\r\n"; settings.Encoding = Encoding.UTF8; //settings.OmitXmlDeclaration = true; // 不生成声明头 using (XmlWriter xmlWriter = XmlWriter.Create(stream, settings)) { // 强制指定命名空间,覆盖默认的命名空间 XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(); namespaces.Add(string.Empty, string.Empty); serializer.Serialize(xmlWriter, obj, namespaces); xmlWriter.Close(); }; stream.Close();
时间: 2024-10-14 00:20:14