I'm currently using
DataContractSerializer dcs = new DataContractSerializer(typeof(T));
XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateTextWriter(filestream, Encoding.UTF8);
dcs.WriteObject(xdw, obj);
In order to write out XML, I've heard good things about the WCF DataContractSerializer in terms of it's performance, and ability to provide forwards compatibility.
However, it's impossible to pass in settings to XmlDictionaryWriter.
I don't 100% understand the differences between XmlDictionaryWriter and a normal XmlWriter with custom settings, and it's impossible to tweak the settings of XmlDictionaryWriter as far as I'm aware.
So what are the differences between XmlDictionaryWriter and XmlWriter (yes one is a super class, but I'm talking concretely, vs var XmlWriter = XmlWriter.Create(filestream, settings);
)
And what settings can I use in order to imitate XmlDictionaryWriter as close as possible, except for having indentation set to true?
I've currently got
var settings = new XmlWriterSettings
{
Indent = true,
Encoding = Encoding.UTF8,
IndentChars = " "
};
As my settings for the XmlWriter, whereas XmlDictionaryWriter appears to have null Settings. (XmlDictionaryWriter.Settings
is both null and readonly, so that's a bust.)
My end goal is to have formatted XML, so maybe if the changes aren't too severe I can just use a hand created XmlWriter anyway.
Comparing the two using NUnit results in
XmlDictionaryWriter
:
"<Party xmlns=\"http://schemas.datacontract.org/2004/07/HeliSTATS.Test\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><Guests><Larry><Age>12</Age><Friend><Name>John</Name></Friend></Larry><Larry><Age>15</Age><Friend><Name>Mason</Name></Friend></Larry></Guests></Party>"
XmlWriter
:
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Party xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/HeliSTATS.Test\">\r\n <Guests>\r\n <Larry>\r\n <Age>12</Age>\r\n <Friend>\r\n <Name>John</Name>\r\n </Friend>\r\n </Larry>\r\n <Larry>\r\n <Age>15</Age>\r\n <Friend>\r\n <Name>Mason</Name>\r\n </Friend>\r\n </Larry>\r\n </Guests>\r\n</Party>"