Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to NOT write XML with pretty print from C# DataSet

Tags:

c#

xml

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.

like image 736
Timothy Carter Avatar asked Jan 08 '09 16:01

Timothy Carter


3 Answers

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);
  }
}
like image 190
casperOne Avatar answered Oct 20 '22 07:10

casperOne


Even easier than using XmlWriterSettings:

XmlTextWriter xml = new XmlTextWriter(fileName, Encoding.UTF8) 
    { Formatting = Formatting.None };
dataSet.WriteXml(xml);
like image 35
atsjoo Avatar answered Oct 20 '22 07:10

atsjoo


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);
like image 37
cjk Avatar answered Oct 20 '22 05:10

cjk