XML Generator


Introduction:

This article is about advance use of reflection package in Csharp. 

About Project:

This project containing three class file. 

  1. XMLGenerator.cs
  2. Employee.cs
  3. MainXMLGenerator.cs

XMLGenerator is a general class file which can generate XML for any object depending on property defined in that object. Employee class is a class which is containing some general detail about employee. MainXMLGenrator is Main class which is controlling execution and printing XML string of employee object.

Output generated by this project is:

<?
xml version="1.0" ?>
<
Employee>
<
EmpCode>E01</EmpCode>
<
EmpName>Shrijeet Nair</EmpName>
<
EmpAddress>Mumbai</EmpAddress>
<
EmpStatus>Single</EmpStatus>
</
Employee>

Main Logical Part of the project:

Main Logical part of the project is XMLGenerator in which we having a function string GetXML(Object)

/// <summary>
/// Function provide detail about the passing object.
/// </summary>
public string GetXml(object mPassingObject)
{
string xmlDoc="";
string fieldValue = "";
string fieldTag;
Type mType;
PropertyInfo[] mProperty;
mType = mPassingObject.GetType();
mProperty = mType.GetProperties();
xmlDoc = xmlDoc + PutInitialHeadTag(mType.Name);
foreach(PropertyInfo mPropertyInformation in mProperty)
{
fieldValue = mPropertyInformation.GetValue(mPassingObject,
null).ToString();
fieldTag=PutTag(mPropertyInformation.Name,fieldValue);
xmlDoc = xmlDoc+fieldTag+"\n";
}
xmlDoc = xmlDoc + PutLastHeadTag(mType.Name);
return xmlDoc;
}

which is generates the XML string corresponding to passed object ..depending on the property defined in that object.This class also contain some general supporting tag for XML generation. This class is general class you can also generate library of this class and you can use this class in any application.

Main Execution Part:

using System;
namespace Shrijeet.XMLGenerator
{
/// <summary>
/// Summary description for MainXMLGenerator.
/// </summary>
public class MainXMLGenerator
{
public static void Main()
{
Employee mEmp =
new Employee("E01","Shrijeet Nair","Mumbai","Single");
XMLGenerator mXml =
new XMLGenerator();
string XMLDoc = mXml.GetXMLHead();
XMLDoc = XMLDoc + mXml.GetXml(mEmp);
Console.WriteLine(XMLDoc);
Console.ReadLine();
}
}
}


Similar Articles