从xmlserializer中删除编码

本文关键字:编码 删除 xmlserializer | 更新日期: 2023-09-27 17:58:52

我正在使用以下代码创建一个xml文档-

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

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

感谢

从xmlserializer中删除编码

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

假设完全删除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标头中删除编码,请将null编码的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("<?xml version='"1.0'" encoding='"utf-8'"?>", "");

感谢这个博客帮助我编写代码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)