How can I make the xmlserializer only serialize plain xml?

岁酱吖の 提交于 2019-11-26 17:59:28

问题


I need to get plain xml, without the <?xml version="1.0" encoding="utf-16"?> at the beginning and xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" in first element from XmlSerializer. How can I do it?


回答1:


To put this all together - this works perfectly for me:

    // To Clean XML
    public string SerializeToString<T>(T value)
    {
        var emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
        var serializer = new XmlSerializer(value.GetType());
        var settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.OmitXmlDeclaration = true;

        using (var stream = new StringWriter())
        using (var writer = XmlWriter.Create(stream, settings))
        {
            serializer.Serialize(writer, value, emptyNamespaces);
            return stream.ToString();
        }
    }



回答2:


Use the XmlSerializer.Serialize method overload where you can specify custom namespaces and pass there this.

var emptyNs = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
serializer.Serialize(xmlWriter, objectToSerialze, emptyNs);

passing null or empty array won't do the trick




回答3:


You can use XmlWriterSettings and set the property OmitXmlDeclaration to true as described in the msdn. Then use the XmlSerializer.Serialize(xmlWriter, objectToSerialize) as described here.




回答4:


This will write the XML to a file instead of a string. Object ticket is the object that I am serializing.

Namespaces used:

using System.Xml;
using System.Xml.Serialization;

Code:

XmlSerializerNamespaces emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });

XmlSerializer serializer = new XmlSerializer(typeof(ticket));

XmlWriterSettings settings = new XmlWriterSettings
{
    Indent = true,
    OmitXmlDeclaration = true
};

using (XmlWriter xmlWriter = XmlWriter.Create(fullPathFileName, settings))
{
    serializer.Serialize(xmlWriter, ticket, emptyNamespaces); 
}


来源:https://stackoverflow.com/questions/1772004/how-can-i-make-the-xmlserializer-only-serialize-plain-xml

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