65.9K
CodeProject is changing. Read more.
Home

Loading XML Data Using Generics and Reflection

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.23/5 (4 votes)

Jul 21, 2007

CPOL
viewsIcon

22642

downloadIcon

141

A generic method that takes the XML node list and type and loads the XML data in a node of the supplied type.

Introduction

If used properly, Generics and Reflection together can do magic. I am not a big magician but I have put up a small sample to read and load XML data generically.

Scenario: Say you have non-OLTP'ish data which you don't want to hard code in your application but place in XML (which I did) and load the data at the start of your application, may be to cache or use directly.

In this example I have two sets of data: site URLs (you don't need to do this, SiteMap in 2.0 is great, this is just for the sample) and states of different countries (here I am using those of USA).

The namespaces in use are System.xml (to load and XPath the XML) and System.Reflection.

private static Collection<T> Get<T>(XmlNodeList nodeList)
               where T : new()
{
    Collection<T> collOfT = new Collection<T>();

    foreach (XmlNode node in nodeList)
    {
        T t = new T();

        PropertyInfo[] propertiesOfT = typeof(T).GetProperties();

        foreach (PropertyInfo property in propertiesOfT)
        {
            string value = node.Attributes[property.Name].Value.ToString();

            property.SetValue(t, value, null);
        }

        collOfT.Add(t);
    }

    return collOfT;
}

The XML:

<?xml version="1.0"?>
<Data>
    <SiteUrls>
        <Root>
            <Url Key = "Home" Path = "Home.htm"></Url>
            <Url Key = "AdminHome" Path = "Admin.htm"></Url>
            <Url Key = "ManagementHome" Path = "Manage.htm"></Url>
        </Root>
    </SiteUrls>

    <Country>
        <USA>
            <State Abbr="AL" Name ="Alabama" />
            <State Abbr="TX" Name ="Texas" />
            <State Abbr="NC" Name ="North Carolina" />
            <State Abbr="MS" Name ="Mississippi" />
            <State Abbr="WV" Name ="West Virginia" />
        </USA>
    </Country>
</Data>