Friday, 11 July 2014

Using XML Part 2

XML does not have to be as simple as the previous example. XML can be serialized. Serialization allows the user to read or write data to an object which can then be later manipulated. A good example of this would be a school mark book.

A class contains 10 students. Every day, they have 5 lessons which they may or may not have homework in. If there is a homework, the mark has to be stored. This is a perfect example for serialized data. To start with, the XML file would look like this:


The code has to be tagged in the source files as [Serializable] in order for the code to work.

To deserialize code from XML, it is as simple as this (FormList is a class which is used to hold the serialized XML)

FormList f;
f = null;

var s = new XmlSerializer(typeof(FormList));
var r = new StreamReader(place + "designer-test.xml");
f = (FormList)s.Deserialize(r);

The FormList looks like this

public class FormList
    private List forms;

    public FormList()
       forms = new List();
    public FormData[] Forms
       get { return this.forms.ToArray(); }
       set { this.forms = new List(value); }

public class FormData
   public List elements;
   public List question;
   public FormData()
      elements = new List();
      question = new List();

   public string WinName { get; set; }
   public int WinWidth { get; set; }
   public int WinHeight { get; set; }
   public string WinTitle { get; set; }
   public int BackLink { get; set; }
   public int ForwardLink { get; set; }
   public int PageNumber { get; set; }
   public int ElementNos { get; set; }

   public Element[] Elements
      get { return this.elements.ToArray(); }
      set { this.elements = new List(value); }

   public Qs[] questions
      get { return this.question.ToArray(); }
      set { this.question = new List(value); }

Forms uses FormData which is what that does the leg work. Note it is the class that is Serializable not the methods.

No comments:

Post a Comment