Click here to Skip to main content
15,884,388 members
Articles / Programming Languages / C#

Reflection to Read XML

Rate me:
Please Sign up or sign in to vote.
2.00/5 (2 votes)
16 Nov 2009CPOL1 min read 22.6K   383   5   4
How Reflection can be used to populate XML data to BO

Introduction

By deserializing XML file, data can be loaded into objects. Suppose you have a legacy application that saves data as an XML file, and you have a new application whose structure is entirely different from the old application. But the new application should be able to load the old application files. In this case, deserialization would not be a solution.

Using Reflection and XmlReader, old XML files can be populated to new application objects.

Using the Code

The sample application can import an old employee file, create a new employee file, and load the selected file. The following figure shows an imported employee file.

Image 1

Adding and loading files are common functionality. Let us see how importing an old file into a new class structure works!!!

First, we have to map old properties to new properties.This is done by Mapper.xml.
Following mapper file maps ,"EmployeeID","EmployeeName" and "EmployeeSalary" properties to new properties. Object information is also included. Type is required in case you have user defined data types.

XML
<Mapper>
  <EmployeeID Object="EmployeeBO" Property="ID" Type="String" />
  <EmployeeName Object="EmployeeBO" Property="Name" Type="String" />
  <EmployeeSalary Object="EmployeeBO" Property="Salary" Type="String" />
</Mapper>

Now it is time to read the XML.
This is done by XMLReader. When element/attribute is read, use this element/attribute as XPath to retrieve respective object and property name from Mapper.xml. Using this object information and reflection, get property information and copy the value to new property.
The following code explains the same.

That's it!!! Your old file is migrated to a new application.

C#
public void LoadXMLToBO(Stream  stream, object dataObject)
  {
      if (stream !=null && dataObject != null)
      {
          XmlReader reader = XmlReader.Create(stream);
          while (reader.Read())
          {
              reader.MoveToContent();
              switch (reader .NodeType)
              {
                  case XmlNodeType.Element:
                      while (reader.MoveToNextAttribute())
                      {
                          ProcessXmlData(reader.Name, reader.Value, dataObject);
                      }
                      break;
                  case XmlNodeType.Text:
                      ProcessXmlData(reader.Name, reader.Value, dataObject);
                      break;
              }
          }
      }
   }
C#
private  void ProcessXmlData(string strNodeName,string strValue,object dataObject)
   {
       if (!string.IsNullOrEmpty(strNodeName) && !string.IsNullOrEmpty(strValue))
       {
             //use node name as XPath
         XmlNode xNode= mapperDoc.SelectSingleNode("Mapper//" + strNodeName);
          if (xNode != null)
          {
            switch (xNode.Attributes["Object"].Value)
            {
               //convert data object to EmployeeBO
               case "EmployeeBO":
                 EmployeeBO employeeBO = dataObject as EmployeeBO;
                 SetValue(xNode.Attributes["Property"].Value, strValue, dataObject);
                 break;
            }
          }
       }
   }
C#
private void SetValue(string strPoperty,string strValue,object dataObject)
  {
      //Find property by reflection
      PropertyInfo property = FindProperty(strPoperty, dataObject);
      if (property != null)
      {
          property.SetValue(dataObject, strValue, null);
      }
  }
C#
private  PropertyInfo FindProperty(string strProperty, object dataObject)
 {
     PropertyInfo property = null;
     if (!string.IsNullOrEmpty(strProperty) && dataObject != null)
      {
         Type objDataType = dataObject.GetType();
         List<PropertyInfo> objPropInfo = 
                  objDataType.GetProperties().ToList<PropertyInfo>();
         for (int i = 0; i < objPropInfo.Count; i++)
         {
           if (objPropInfo == null) continue;
           if (objPropInfo[i].Name == strProperty)
             {
                property = objPropInfo[i];
                 break;
             }
          }
        }
        return property;
    }    

Points of Interest

Instead of XMLReader, XMLDocument can also be used.
In switch case of "ProcessXmlData", you can include other objects as well depending on to the object the property belongs to. That is the reason Mapper.xml has "Object" attribute.

History

  • Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Not Active18-Nov-09 4:53
mentorNot Active18-Nov-09 4:53 
Reflection is not needed, a XSLT can transform one XML structure to another.
GeneralRe: My vote of 1 Pin
KN.Sudha19-Nov-09 0:23
KN.Sudha19-Nov-09 0:23 
GeneralThoughts Pin
PIEBALDconsult17-Nov-09 3:49
mvePIEBALDconsult17-Nov-09 3:49 
GeneralRe: Thoughts Pin
KN.Sudha19-Nov-09 0:14
KN.Sudha19-Nov-09 0:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.