Building an Xml Serialization Provider

October 13th, 2008 by John Sedlak Leave a reply »

These methods are very straight forward and really need no explanation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private XmlNode CreateSimpleNode(object obj, XmlNodeAttribute nodeAttribute, XmlDocument doc)
{
    XmlNode node = null;
 
    node = doc.CreateElement(nodeAttribute.Name);
 
    AppendTypeAttribute(obj, doc, node);
 
    node.InnerText = obj.ToString();
 
    return node;
}
 
private void AppendTypeAttribute(object obj, XmlDocument doc, XmlNode node)
{
    Type objectType = obj.GetType();
 
    XmlAttribute typeAttribute = doc.CreateAttribute("DataType");
    typeAttribute.Value = string.Format("{0}.{1}", objectType.Namespace, objectType.Name);
 
    node.Attributes.Append(typeAttribute);
}

Stay tuned for part two which will tackle deserializing the Xml files! The following code is a driver program for testing serialization.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using System.Xml;
using FocusedGames.Xml;
 
namespace XmlSerialization
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlProvider provider = new XmlProvider();
 
            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
 
            doc.AppendChild(dec);
 
            doc.AppendChild(provider.Serialize(new DataObject(), doc));
 
            doc.Save("data.xml");
        }
    }
 
    [XmlNode("DataObject", XmlNodeType.Complex)]
    public class DataObject
    {
        public DataObject()
        {
            Text = "Hello, world!";
 
            Data = new DataObject2Child();
        }
 
        [XmlNode("Text", XmlNodeType.Simple)]
        public string Text { get; set; }
 
        [XmlNode("Data", XmlNodeType.Complex)]
        public DataObject2 Data { get; set; }
    }
 
    [XmlNode("DataObject2", XmlNodeType.Complex)]
    public class DataObject2
    {
        public DataObject2()
        {
            Text = "HELLO";
        }
 
        [XmlNode("Text", XmlNodeType.Simple)]
        public string Text { get; set; }
    }
 
    public class DataObject2Child : DataObject2 {
        public DataObject2Child()
        {
            Text = "HELLO CHILD";
        }
    }
}
Advertisement

Leave a Reply

You must be logged in to post a comment.