Click here to Skip to main content
15,896,111 members
Articles / Programming Languages / XML

A Custom .NET XML Serialization Library

Rate me:
Please Sign up or sign in to vote.
4.43/5 (4 votes)
25 Jan 200611 min read 42.3K   432   21  
Describes a custom XML serialization library, with functionality to compare for, and to combine differences
using System;
using System.Collections;

namespace Wxv.Wml.IO
{
	/// <summary>
	/// An abstract WmlWriter class which implements a reader over a newly created
	/// IWmlNode structure
	/// </summary>
	public abstract class WmlNodeWriter : WmlWriter
	{
		private ArrayList nodes = new ArrayList();
		
		protected IWmlNode documentNode;
		private bool wroteDocumentNode;

		public WmlNodeWriter () 
		{
		}

		public override void WriteBeginNode (string name, int id, string val, string deletedValue, WmlNodeState state)
		{
			// ignore the first write to the root node
			if (!wroteDocumentNode)
			{
				if (name != Wml.DocumentName)
					throw new Exception ("Invalid document name");

				wroteDocumentNode = true;
                nodes.Add (documentNode);
				return;
			}
			else if (nodes.Count == 0)
				throw new Exception ("Mismatched WriteBeginNode call in WmlNodeWriter");

			IWmlNode parentNode = (IWmlNode) nodes [nodes.Count - 1];
			if (((parentNode.State == WmlNodeState.Added) || (parentNode.State == WmlNodeState.Deleted))
			 && ((state == WmlNodeState.NoChange) || (parentNode.State == WmlNodeState.Updated)))
				throw new Exception ("Cannot add a child node state of NoChange or Updated to a parent node with the state of Added or Deleted");

			IWmlNode childNode = parentNode.Create (name, id, val, deletedValue, state);
			nodes.Add (childNode);
		}
		
		public override void WriteEndNode ()
		{
			if (nodes.Count == 0)
				throw new Exception ("Mismatched WriteBeginNode call in WmlNodeWriter");
			
			// weve finished writing the child node, add it to the parent
			if (nodes.Count > 1) 
			{
				IWmlNode parentNode = (IWmlNode) nodes [nodes.Count - 2];
				IWmlNode childNode = (IWmlNode) nodes [nodes.Count - 1];

				// if child node is null, it was a deleted node, so ignore
				if (childNode != null)
					parentNode.Add (childNode);
			}

			nodes.RemoveAt (nodes.Count - 1);
		}

		public override void Dispose()
		{
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


Written By
Web Developer
New Zealand New Zealand
Im a Software Developer working in Auckland, New Zealand. When i was a lot shorter, i started programming in Atari Basic, though these days its mostly C#, and a bit of java (mostly the caffinated kind).

Comments and Discussions