XML Deserialization


So, you have an XML document, your programming in Visual Studio 11 for your new Windows 8 Metro app, and you need to access the data within?  I’m here to help…

DE serializing your XML document is very simple.  First you’ll need to define a CLASS object the way your XML document is…

Here’s my example XML document:

<?xml version="1.0" encoding="UTF-8" ?>

<Congress>
  <Regions>
    <Region>
      <Title>Northeast</Title>

      <States>
        <State>
          <Title>Connecticut</Title>

          <Districts>
            <District>
              <Title>District 1</Title>
              <SubTitle>Larson, John B.</SubTitle>
            </District>
          </Districts>
        </State>
      </States>
    </Region>
  </Regions>
</Congress>

This is an example of an XML document I’m currently using in my contest application.  As you can see there can be multiple Regions, States or Districts.  Each organized in sub objects… I am showing you only one of each since it would get pretty long otherwise…

Now, we’ll need a few classes organized just like this XML document:

[XmlRoot("Congress")]
public class clsCongress
{
    [XmlArray("Regions")]
    [XmlArrayItem("Region", typeof(clsRegion))]
    public clsRegion[] Region { get; set; }
}

[XmlRoot("Regions")]
public class clsRegion
{
    [XmlElement("Title")]
    public string Title { get; set; }

    [XmlArray("States")]
    [XmlArrayItem("State", typeof(clsState))] 
    public clsState[] State { get; set; }
}

[XmlRoot("States")]
public class clsState
{
    [XmlElement("Title")]
    public string Title { get; set; }
        
    [XmlArray("Districts")]
    [XmlArrayItem("District", typeof(clsDistrict))]
    public clsDistrict[] District { get; set; }
}

[XmlRoot("Districts")]
public class clsDistrict
{        
    [XmlElement("Title")]
    public string Title { get; set; }
        
    [XmlElement("SubTitle")]
    public string SubTitle { get; set; }
}


As you can see form my class objects, you’ll need to specify the XmlRoot for each class as well as each XmlElement so everything maps correctly.  In my example, the elements match, but they don’t have to so long as they’re mapped with the XmlElement tag.

Now, I know you can find this code anywhere on the net… but what they don’t go into detail explaining is the array variables I have shown here. 

In my example, I have Congress which is made up of multiple Regions, which is made up of multiple States, and Districts.  In my example here, I demonstrate how to get multiple sub-objects pulled in easily and quickly.

Here is the code I use to load up the XML text, oh and I’m downloading this content using the new fancy async features from VS11 and Windows 8:

internal async Task PullRegionsAsync(Uri baseUri)
{
    string baseUrl = "https://danielheth.com/myexample.xml";

    //download the data xml
    //http://msdn.microsoft.com/en-us/library/windows/apps/system.net.http.httpclienthandler.maxrequestcontentbuffersize(v=VS.110).aspx
    //says there is a 65k limit on the size of what this function will download...
    var client = new HttpClient();
    var response = await client.GetAsync(baseUrl + "Data.xml");
            
    //------------------------------------------------
    //convert xml into an easily digestable object
    clsCongress congress = null;
    XmlSerializer des = new XmlSerializer(typeof(clsCongress));
    congress = (clsCongress)des.Deserialize(response.Content.ContentReadStream);
    //------------------------------------------------

    foreach (clsRegion r in congress.Region)
    {
        string RegionTitle = r.Title;

        foreach (clsState s in r.State)
        {
            string StateTitle = s.Title;

            foreach (clsDistrict d in s.District)
            {
                string DistrictTitle = d.Title;
            }
        }
    }
}

There you have it… deserializing your XML document into an easily digestible object within C#.

If you have any questions or comments please leave them below…

Advertisements

One thought on “XML Deserialization

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s