Convert XML to Class and Extract XML response to Entity using Generics and Reflection

I just was in need for a simple way to extract XML response and generate a class first  from the XML

and then later use this class to extract XML response to Entity using Generics and Reflection

The Power of Generics is that it will reduce the code  that can be applied to many response

This for me at least is Alternative and simple than Microsoft XSD tool

I will attach a complete solution that make it easy for you to experiment the new tool.

image

let us start:

this is basic xml that represent a store :

<?xml version="1.0"?>
<response result="good">
  <results>
    <stores count="1">
      <store>
        <SID>4</SID>
        <Name>St. Michael's Alley</Name>
        <Twitter>StMichaelsAlley</Twitter>
        <Facebook></Facebook>
        <Website>http://www.stmikes.com</Website>
        <Description>
          Food Services
        </Description>
        <Category>1</Category>
        <TwitterSearch>Palo Alto Brunch</TwitterSearch>
        <Reviews>
          Yelpers love St. Michael's Alley, giving it 4 out of 5 stars
        </Reviews>
        <PID>12</PID>
        <ImageVersion>1</ImageVersion>
        <SendEmail>0</SendEmail>
        <Phone>6503262530</Phone>
        <Street>140 Homer Avenue</Street>
        <City>Palo Alto</City>
        <State>CA</State>
        <Zip>94301</Zip>
        <ID>7</ID>
        <Image>http://www.chompon.com/uploads/stores/4.jpg</Image>
        <ImageSmall>http://www.chompon.com/uploads/stores/4_s.jpg</ImageSmall>
      </store>
    </stores>
  </results>
</response>
so we need first to convert this store to class and save it to our project
cause we will use it later to Extract the XML Response:
public string ConvertXMLToClass(string XML, string Tag)
        {
            XmlDocument document = new XmlDocument();
            document.LoadXml(XML);
            //Gets all the tags with tag name row
            XmlNodeList nodeList = document.GetElementsByTagName(Tag);
            //Loop through each and every node
            StringBuilder sb = new StringBuilder();
            sb.Append("public ").Append(Tag).Append("\r\n{\r\n");

            foreach (XmlNode node in nodeList)
            {
                foreach (XmlNode xmlAtr in node.ChildNodes)
                {
                    sb.Append("\tpublic string " + xmlAtr.Name + " {get;set;}\r\n");
                }
                sb.Append("}");
            }
            return sb.ToString();
        }
 

so now we had converted it to a class that you can save it to your project to use it for next step

Note: You can see how to create Objects and fill it from source text at run time if you need this

Now we are ready to extract the XML response , this is basic XML response that represent stores:

<?xml version="1.0"?>
<response result="good">
  <results>
    <stores count="2">
      <store>
        <SID>4</SID>
        <Name>St. Michael's Alley</Name>
        <Twitter>StMichaelsAlley</Twitter>
        ......
      </store>

      <store>
        <SID>5</SID>
        <Name>Glendon Shop</Name>
        <Twitter>GLS</Twitter>
        ......
      </store>
      ...
    </stores>
  </results>
</response>
Now let us see the power of Generics and Reflection to extract the data and fill our Entity:
public List<T> Parse<T>(string XMLResponse) where T : new()
        {
            List<T> tObjects = new List<T>();
            XmlDocument document = new XmlDocument();
            document.LoadXml(XMLResponse);
            //Gets all the tags with tag name row
            XmlNodeList nodeList = document.GetElementsByTagName(new T().GetType().Name.ToLower());
            //Loop through each and every node
            foreach (XmlNode node in nodeList)
            {
                T tObject = new T();
                foreach (XmlNode xmlAtr in node.ChildNodes)
                {
                    tObject.GetType().GetProperty(xmlAtr.Name).SetValue(tObject, xmlAtr.InnerText, null);
                }
                tObjects.Add(tObject);
            }
            //now objectList has your required values.
            return tObjects;
        }

As you can see here we can use the same function for many response which worth it actually the C# team

introduce  where T : new()  , which make it possible for us to create an Object from unknown type at

compile time to be able to use it at run time to fill it.

I hope this find a way to introduce ideas of the power of Generics and Reflection.

If you like it or have any suggestions kindly leave me a comment.

XMLToClass.zip

Published Friday, March 04, 2011 2:04 AM by Haitham Khedre

Comments

# re: Convert XML to Class and Extract XML response to Entity using Generics and Reflection

Friday, July 29, 2011 11:24 PM by Moncler jackets outlet

This site is very helpful and very informative for me. i am so glad to find out your blog immediately. thanks for sharing with us.<a href="www.jacketsmoncleroutlet.com/" title="Moncler jackets outlet">Moncler jackets outlet</a>

# re: Convert XML to Class and Extract XML response to Entity using Generics and Reflection

Sunday, July 31, 2011 10:08 PM by baseball caps

Advantageously, the post is really the freshest on this valuable topic. I agree with your conclusions and will eagerly look forward to your next updates.<a href="www.baseballcaps-forsale.com/" title="baseball caps">baseball caps</a>

# re: Convert XML to Class and Extract XML response to Entity using Generics and Reflection

Tuesday, August 02, 2011 9:49 PM by Wholesale sunglasses

Enjoyed quickly looking over your blog and will bookmark for future use, thanks<a href="www.2011wholesalesunglasses.com/" title="Wholesale sunglasses">Wholesale sunglasses</a>

# re: Convert XML to Class and Extract XML response to Entity using Generics and Reflection

Thursday, August 11, 2011 9:28 PM by Canada Goose sale

Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog.

# re: Convert XML to Class and Extract XML response to Entity using Generics and Reflection

Friday, August 12, 2011 2:46 AM by goose parka

Thats specificaly what I was searching for thanks. I will check you site more ofthen.great job on the blog.[url=http://www.canadagoose2u.com/]goose parka[/url]

# re: Convert XML to Class and Extract XML response to Entity using Generics and Reflection

Tuesday, August 30, 2011 3:27 AM by baseball caps

Thanks for taking this opportunity to converse about  this, I feel strongly  about this and I enjoy learning about this subject.

# re: Convert XML to Class and Extract XML response to Entity using Generics and Reflection

Tuesday, August 30, 2011 3:54 AM by burberry bags outlet online

Nice content, I trust this is a nice blog. Wish to see fresh content next time.

# re: Convert XML to Class and Extract XML response to Entity using Generics and Reflection

Wednesday, August 31, 2011 2:57 AM by Prada handbags outlet

Your blog is perfect, and I like this article. I find the information I need. I think I can find more useful information here, thanks.<a href="www.pradabagsoutletstore.com/" title="Prada handbags outlet">Prada handbags outlet</a>

# re: Convert XML to Class and Extract XML response to Entity using Generics and Reflection

Monday, September 05, 2011 9:01 PM by Abercrombie outlet sale

Just want to say your article is brilliant. The clarity in your post is simply impressive and i can assume you are an expert on this subject.

# re: Convert XML to Class and Extract XML response to Entity using Generics and Reflection

Wednesday, September 07, 2011 10:04 PM by sac louis vuitton

Very nice post. I really enjoy the reading. I  come here from the google while searching for some good article.Thanks!<a href="www.frlouisvuittonsac.com/" title="sac louis vuitton">sac louis vuitton</a>

# re: Convert XML to Class and Extract XML response to Entity using Generics and Reflection

Friday, September 09, 2011 11:49 PM by designer bags

The theme is really attractive. Congratulations to the author of the blog!

# re: Convert XML to Class and Extract XML response to Entity using Generics and Reflection

Monday, September 12, 2011 10:34 PM by cheap prada handbags

I am glad to found such useful post. I really increased my knowledge after read your post which will be beneficial for me.<a href="www.cheappradahandbagsonline.com/" title="cheap prada handbags">cheap prada handbags</a>

# re: Convert XML to Class and Extract XML response to Entity using Generics and Reflection

Sunday, November 06, 2011 12:37 AM by HaNUKVDMzHAueaMK

IQ3uH1 Good! Wish everybody wrote so:DD

# re: Convert XML to Class and Extract XML response to Entity using Generics and Reflection

Wednesday, March 21, 2012 12:58 AM by Hosted Ecommerce software

Thanks for sharing these codes.

# re: Convert XML to Class and Extract XML response to Entity using Generics and Reflection

Thursday, March 22, 2012 5:24 AM by starting up a new business

This is what I have been searching in many websites and I finally found it here. Amazing article. I am so impressed. Could never think of such a thing is possible with it...I think you have a great  knowledge especially while dealings with such subjects.

# re: Convert XML to Class and Extract XML response to Entity using Generics and Reflection

Monday, May 07, 2012 7:29 AM by FzjkNyzxlWMhA

Enjoyed every bit of your blog post.Really looking forward to read more. Want more.

Leave a Comment

(required) 
(required) 
(optional)
(required)