Home > Posts > HowTo: format XML output of DataContractSerializer

HowTo: format XML output of DataContractSerializer

based on the other samples posted at StackOverflow on how to format XML created by DataContractSerializer, that use XmlWriter, here’s a version (from ClipFlair source code) that works with streams (and Ionic.Zip library in specific).

It also shows how the code is when you don’t apply formatting (using conditional compilation).  Just comment out the #define (prefix it with //) to make it write unformatted XML.

 

#define WRITE_FORMATTED_XML

using System.Xml;

namespace ClipFlair.Windows
{

  public partial class BaseWindow : FloatingWindow
  {

    //...

    #if WRITE_FORMATTED_XML
    private static XmlWriterSettings XML_WRITER_SETTINGS = 
new XmlWriterSettings() { Indent=true, IndentChars=" "}; #endif //... public virtual void SaveOptions(ZipFile zip, string zipFolder = "")
//THIS IS THE CORE SAVING LOGIC { if (SavingOptions != null) SavingOptions(this, null); //notify any listeners View.Busy = true; try { ZipEntry optionsXML =
zip.AddEntry(zipFolder + "/" + View.GetType().FullName + ".options.xml", new WriteDelegate((entryName, stream) => { DataContractSerializer serializer =
new DataContractSerializer(View.GetType());
//assuming current View isn't null #if WRITE_FORMATTED_XML using (XmlWriter writer = XmlWriter.Create(stream, XML_WRITER_SETTINGS)) serializer.WriteObject(writer, View); #else serializer.WriteObject(stream, View); #endif })); } catch (Exception e) { MessageBox.Show("ClipFlair options save failed: " + e.Message); } finally { View.Busy = false; //in any case (error or not) clear the Busy flag } if (SavedOptions != null) SavedOptions(this, null); //notify any listeners } //... } }
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: