We can serialize and deserialize complex classes to xml and vice-versa. For example we have a xml:
<?xml version="1.0" encoding="utf-8" ?> <Settings> <UIObject> <Question>ABC</Question> <Question>XYZ</Question> <Question>PQR</Question> </UIObject> <ApplicationRestart> <Question>Resume</Question> <Question>Restart</Question> </ApplicationRestart> <QuestionNumbering> <Question>A</Question> <Question>I</Question> <Question>1</Question> </QuestionNumbering> <AnswerNumbering> <Question>A</Question> <Question>I</Question> <Question>1</Question> </AnswerNumbering> <Seperator> <Question>,</Question> <Question>.</Question> </Seperator> </Settings>
Then we need to deserialize it. Here we create a class, say Settings to create root note of the xml document.
All the other nested sub-nodes are created as a list here. Therefore the complete class will be as:
public class Settings
{
[XmlArray("UIObject")]
[XmlArrayItem(ElementName = "Question")]
public List<string> UIObject { get; set; }
[XmlArray("ApplicationRestart")]
[XmlArrayItem(ElementName = "Question")]
public List<string> ApplicationRestart { get; set; }
[XmlArray("QuestionNumbering")]
[XmlArrayItem(ElementName = "Question")]
public List<string> QuestionNumbering { get; set; }
[XmlArray("AnswerNumbering")]
[XmlArrayItem(ElementName = "Question")]
public List<string> AnswerNumbering { get; set; }
[XmlArray("Seperator")]
[XmlArrayItem(ElementName = "Question")]
public List<string> Seperator { get; set; }
}
This class/model will use as base class to perform serialization/deserialization. Here is a example to complete these operations:
XMLUtility objXml = new XMLUtility();
Settings objSetting = new Settings();
List<string> Ques = new List<string>();
Ques.Add("RADIONBUTTON");
Ques.Add("CHECKBOX");
Ques.Add("DROPDOWNLIST");
objSetting.UIObject = Ques;
Ques = new List<string>();
Ques.Add("Resume");
Ques.Add("Restart");
objSetting.ApplicationRestart = Ques;
Ques = new List<string>();
Ques.Add("A");
Ques.Add("I");
Ques.Add("1");
objSetting.QuestionNumbering = Ques;
Ques = new List<string>();
Ques.Add("A");
Ques.Add("I");
Ques.Add("1");
objSetting.AnswerNumbering = Ques;
Ques = new List<string>();
Ques.Add(",");
Ques.Add(".");
objSetting.Seperator = Ques;
/// convert object to xml string
string xml = objXml.CreateXML(objSetting);
Response.Write(xml);
/// convert xml string to object.
Settings obj2 = (Settings)objXml.CreateObject(xml, new Settings());
In this way we can serialize and deserialize even more complex classes.