remove encoding from xmlserializer

一笑奈何 提交于 2019-12-31 21:57:12

问题


I am using the following code to create an xml document -

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

this works great in creating the xml file with no namespace attributes. i would like to also have no encoding attribute in the root element, but I cannot find a way to do it. Does anyone have any idea if this can be done?

Thanks


回答1:


Old answer removed and update with new solution:

Assuming that it's ok to remove the xml declaration completly, because it makes not much sense without the encoding attribute:

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



回答2:


To remove encoding from XML header pass TextWriter with null encoding to XmlSerializer:

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

Explanation

XmlTextWriter uses encoding from TextWriter passed in constructor:

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

It uses this encoding when generating XML:

// Snippet from XmlTextWriter.StartDocument
if (this.encoding != null)
{
  builder.Append(" encoding=");
  ...



回答3:


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\"?>", "");



回答4:


Credit to this blog for helping me with my code http://blog.dotnetclr.com/archive/2008/01/29/removing-declaration-and-namespaces-from-xml-serialization.aspx

here's my solution, same idea, but in VB.NET and a little clearer in my opinion.

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)


来源:https://stackoverflow.com/questions/6297249/remove-encoding-from-xmlserializer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!