从xmlserializer中删除编码

我使用以下代码创建一个xml文档 –

XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); new XmlSerializer(typeof(docket)).Serialize(Console.Out, i, ns); 

这非常适合创建没有命名空间属性的xml文件。 我想在根元素中也没有编码属性,但我找不到办法。 有没有人知道这是否可以做到?

谢谢

删除旧答案并使用新解决方案进行更新:

假设可以完全删除xml声明,因为没有编码属性它没有多大意义:

 XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); using (XmlWriter writer = XmlWriter.Create(Console.Out, new XmlWriterSettings { OmitXmlDeclaration = true})) { new XmlSerializer(typeof (SomeType)).Serialize(writer, new SomeType(), ns); } 

要从XML头中删除编码 ,请将带有编码的TextWriter传递给XmlSerializer:

 MemoryStream ms = new MemoryStream(); XmlTextWriter w = new XmlTextWriter(ms, null); s.Serialize(w, vs); 

说明

XmlTextWriter使用构造函数中传递的TextWriter编码:

 // XmlTextWriter constructor public XmlTextWriter(TextWriter w) : this() { this.textWriter = w; this.encoding = w.Encoding; .. 

它在生成XML时使用此编码:

 // Snippet from XmlTextWriter.StartDocument if (this.encoding != null) { builder.Append(" encoding="); ... 
 string withEncoding; using (System.IO.MemoryStream memory = new System.IO.MemoryStream()) { using (System.IO.StreamWriter writer = new System.IO.StreamWriter(memory)) { serializer.Serialize(writer, obj, null); using (System.IO.StreamReader reader = new System.IO.StreamReader(memory)) { memory.Position = 0; withEncoding= reader.ReadToEnd(); } } } string withOutEncoding= withEncoding.Replace("", ""); 

感谢这个博客帮助我使用我的代码http://blog.dotnetclr.com/archive/2008/01/29/removing-declaration-and-namespaces-from-xml-serialization.aspx

这是我的解决方案,同样的想法,但在VB.NET中,我认为更清楚一点。

 Dim sw As StreamWriter = New, StreamWriter(req.GetRequestStream,System.Text.Encoding.ASCII) Dim xSerializer As XmlSerializer = New XmlSerializer(GetType(T)) Dim nmsp As XmlSerializerNamespaces = New XmlSerializerNamespaces() nmsp.Add("", "") Dim xWriterSettings As XmlWriterSettings = New XmlWriterSettings() xWriterSettings.OmitXmlDeclaration = True Dim xmlWriter As XmlWriter = xmlWriter.Create(sw, xWriterSettings) xSerializer.Serialize(xmlWriter, someObjectT, nmsp)