Dynamic XML Creation Using .NET Reflection to Access an Object

It's usual to create a XML Document using some information created dynamically. Usually we have a type that have one or more properties (or fields) were are stored all information. Creatting a simple XML accessing to all properties or fields is a loss of time. Eventually, some types have a specific XML element. In that cases, we must manually generate that element, but only that element.

In this simple case, we have a public class were is allocated the information. The class looks like following:

Public Class Identification
{
private string _name = null;
private string _address = null;
public string Name
{
get
{
return _name;
} set
{
_name = value;
}
}  

public string Address
{
get
{
return _address;
}
set
{
_address = value;
}
}
}

Next, we create a instance of Identification:

Identification identification = new Identification();
identification.Name = "Edgar";
identification.Address = "Lisbon"

Finally create XML Document using reflexion to access properties of our Identification instance:

XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", String.Empty);
xmlDoc.PrependChild(xmlDec);
XmlElement elemRoot = xmlDoc.CreateElement("Identification");
xmlDoc.AppendChild(elemRoot);
XmlElement elem = null;
Type idType = identification.GetType();
foreach (PropertyInfo pInfo in idType.GetProperties())
{
object o = pInfo.GetValue(identification, null);
elem = xmlDoc.CreateElement(pInfo.Name);
elem.InnerText = o.ToString();
elemRoot.AppendChild(elem);
}

Now we can serializate XML to a file or print to console. The final result :

< ? xml version="1.0" encoding="utf-8"? >
< Identification >
< Name > Edgar < / Name >
< Address > Lisbon < / Address >
< / Identification >

Up Next
    Ebook Download
    View all
    Learn
    View all