In C# how do you write a DataSet to file without it being written with pretty print?
Using C# and .NET 2.0, I've been using dataSet.WriteXml(fileName, XmlWriteMode.IgnoreSchema), which by default is writing the Xml file with pretty print. The company consuming the Xml files I write suggested that writing without the pretty print will not affect them, and will significantly decrease the size of the files. With a little playing around in the System.Xml namespace, I did find a solution. However, in my searching I did not find the answer anywhere, so I thought it might be helpful to someone else in the future if I posted the question. Also, I wouldn't be surprised at all if there's a better or at least different way of accomplishing this.
For those that don't know (I didn't until today), Xml "pretty print" is:
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<Foo>
<Bar>abc</Bar>
</Foo>
</NewDataSet>
Without pretty print it looks like this:
<?xml version="1.0" encoding="utf-8"?><NewDataSet><Foo><Bar>abc</Bar></Foo></NewDataSet>
Additionally, the size savings was significant, 70mb files are becoming about 40mb. I'll post my solution later today if no one else has.
It's pretty simple, you just have to create an XmlWriter
using an XmlWriterSettings
which has the Indent
property set to false:
// The memory stream for the backing.
using (MemoryStream ms = new MemoryStream())
{
// The settings for the XmlWriter.
XmlWriterSettings settings = new XmlWriterSettings();
// Do not indent.
settings.Indent = false;
// Create the XmlWriter.
using (XmlWriter xmlWriter = XmlWriter.Create(ms, settings))
{
// Write the data set to the writer.
dataSet.WriteXml(xmlWriter);
}
}
Even easier than using XmlWriterSettings:
XmlTextWriter xml = new XmlTextWriter(fileName, Encoding.UTF8)
{ Formatting = Formatting.None };
dataSet.WriteXml(xml);
This is what I would try...:
EDIT: (does not compile, settings need to be added in XmlWriter.Create constructor - but the theory is there.)
DataSet ds = new DataSet();
System.Xml.XmlTextWriter xmlW = new System.Xml.XmlTextWriter("C:\\temp\\dataset.xml");
System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
settings.Indent = false;
settings.NewLineChars = String.Empty;
xmlW.Settings = settings;
ds.WriteXml(xmlW);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With