/*
Copyright (c) 2005, Marc Clifton
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of MyXaml nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
namespace Clifton.Tools.Xml
{
public class Serializer
{
protected MemoryStream ms;
protected XmlTextWriter xtw;
protected string xml;
protected Hashtable arrays;
public XmlTextWriter TextWriter
{
get {return xtw;}
}
public string Xml
{
get {return xml;}
}
public void Start()
{
Start("Objects", true);
}
public void Start(string startElement)
{
Start(startElement, true);
}
public void Start(string startElement, bool preamble)
{
arrays=new Hashtable();
ms=new MemoryStream();
xtw = new XmlTextWriter(ms, Encoding.UTF8);
xtw.Formatting=Formatting.Indented;
xtw.Namespaces=false;
if (preamble)
{
xtw.WriteStartDocument();
xtw.WriteComment("Auto-Serialized");
}
xtw.WriteStartElement(startElement);
}
public void StartElement(string startElement)
{
xtw.WriteStartElement(startElement);
}
public void EndElement()
{
xtw.WriteEndElement();
}
public string Finish()
{
Trace.Assert(xtw != null, "Must call Serializer.Start() first.");
xtw.WriteEndElement();
xtw.Flush();
xtw.Close();
Encoding e8=new UTF8Encoding();
xml=e8.GetString(ms.ToArray(), 1, ms.ToArray().Length-1);
arrays.Clear();
return xml;
}
// simple property serialization
public void Serialize(object obj)
{
Trace.Assert(xtw != null, "Must call Serializer.Start() first.");
Trace.Assert(obj != null, "Cannot serialize a null object.");
Type t=obj.GetType();
xtw.WriteStartElement(t.Name);
foreach(PropertyInfo pi in t.GetProperties())
{
Type propertyType=pi.PropertyType;
// check if the item is an IList
object val=pi.GetValue(obj, null);
// with enum properties, IsPublic==false, even if marked public!
if ( (propertyType.IsSerializable) && (!propertyType.IsArray) && (!(val is IList)) && (pi.CanWrite) && ( (propertyType.IsPublic) || (propertyType.IsEnum) ) )
{
if (val != null)
{
bool isDefaultValue=false;
// look for a default value attribute.
foreach(object attr in pi.GetCustomAttributes(false))
{
if (attr is DefaultValueAttribute)
{
// it exists--compare current value to default value
DefaultValueAttribute dva=(DefaultValueAttribute)attr;
isDefaultValue=val.Equals(dva.Value);
}
}
// only non-default values or properties without a default value are serialized.
if (!isDefaultValue)
{
// do a type conversion to a string, as this yields a deserializable value, rather than what ToString returns.
TypeConverter tc=TypeDescriptor.GetConverter(propertyType);
if (tc.CanConvertTo(typeof(string)))
{
val=tc.ConvertTo(val, typeof(string));
xtw.WriteAttributeString(pi.Name, val.ToString());
}
else
{
Trace.WriteLine("Cannot convert "+pi.Name+" to a string value.");
}
}
}
else
{
// null values not supported!
}
}
}
ExtraAttributes(xtw, obj);
xtw.WriteEndElement();
}
public virtual void ExtraAttributes(XmlTextWriter xtw, object obj)
{
}
}
public abstract class Deserializer
{
public abstract object GetObject(string name);
protected XmlDocument doc;
public void Start(string text)
{
doc=new XmlDocument();
doc.LoadXml(text);
}
public void Start(XmlDocument doc)
{
this.doc=doc;
Deserialize();
}
// for completeness only
public void Finish()
{
}
// simple property deserialization
public void Deserialize()
{
XmlNode n=doc.DocumentElement;
Trace.Assert(doc != null, "Must call Deserializer.Start() first.");
foreach(XmlNode node in n.ChildNodes)
{
Deserialize(node);
}
}
protected void Deserialize(XmlNode node)
{
if (!(node is XmlElement))
{
return;
}
if (node.ChildNodes.Count > 0)
{
foreach(XmlNode childNode in node.ChildNodes)
{
Deserialize(childNode);
}
return;
}
object obj=GetObject(node.Name);
Type t=obj.GetType();
// set all properties that have a default value and not overridden.
foreach(PropertyInfo pi in t.GetProperties())
{
Type propertyType=pi.PropertyType;
// look for a default value attribute.
foreach(object attr in pi.GetCustomAttributes(false))
{
if (attr is DefaultValueAttribute)
{
// it has a default value
DefaultValueAttribute dva=(DefaultValueAttribute)attr;
if (node.Attributes[pi.Name] == null)
{
// assign the default value, as it's not being overridden.
// this reverts the object's property back to the default
pi.SetValue(obj, dva.Value, null);
}
}
}
}
// now parse the xml attributes that are going to change property values
foreach(XmlAttribute attr in node.Attributes)
{
string pname=attr.Name;
string pvalue=attr.Value;
PropertyInfo pi=t.GetProperty(pname);
if (pi != null)
{
TypeConverter tc=TypeDescriptor.GetConverter(pi.PropertyType);
if (tc.CanConvertFrom(typeof(string)))
{
try
{
object val=tc.ConvertFrom(pvalue);
pi.SetValue(obj, val, null);
}
catch(Exception e)
{
Trace.WriteLine("Setting "+pname+" failed:\r\n"+e.Message);
}
}
}
else
{
ExtraAttributes(obj, attr.Name, attr.Value);
}
}
}
public virtual void ExtraAttributes(object obj, string attrName, string val)
{
}
}
}