Reputation: 265131
Is it possible to instruct .NET's XmlSerializer to serialize XML documents to the following format:
<?xml version="1.0"?>
<!DOCTYPE root SYSTEM "root.dtd">
<root>
...
</root>
i.e. XML declaration without the encoding attribute, doctype and then the rest of the document?
Currently I have:
var bomlessUtf8Encoding = new UTF8Encoding(false);
var serializer = new XmlSerializer(typeof(T));
var namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
using (var memoryStream = new MemoryStream())
using (var xmlWriter = XmlWriter.Create(memoryStream, new XmlWriterSettings { Indent = false, Encoding = null }))
{
xmlWriter.WriteDocType(typeof(T).Name, null, ContentSerializer.MlpSvcInit320Dtd, null);
serializer.Serialize(xmlWriter, input, namespaces);
return bomlessUtf8Encoding.GetString(memoryStream.ToArray());
}
but .NET is barking when creating the XmlWriterSettings object due to Encoding being null. Is there a canonical way, or is it easiest to simply serialize to a string and then call .Replace()
on it?
Unfortunately, a third party vendor requires the serialized string to be exactly in this format.
Upvotes: 0
Views: 2838
Reputation: 142
XmlTextWriter
gets you the possibility of remove encoding
attribute. If you pass null
as encoding, xml will be encoded using UTF-8, but encoding
attribute will be removed.
So something like this:
using(var xmlWriter = new XmlTextWriter(memoryStream, null))
should be suitable. You can also set Indent
etc, refer to http://msdn.microsoft.com/pl-pl/library/system.xml.xmltextwriter(v=vs.110).aspx
Upvotes: 1