19Aug/090
Deserialize XML to an Object
One of the more useful tools to have in your toolbox is a method or class to convert an Object to XML and XML to an Object.
Converting XML to an object is very easy.
You need your destination object:
public class PersonObject
{
public string lastName;
public string firstName;
public string gender;
public string email;
public int age;
public int telephone;
public string city;
public string state;
public PersonObject() {}
}
Most likely you will recieve your XML from a web service. Here is some simple code to call a webservice and get the XML response:
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.someurl.com/getPerson?...");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
PersonObject person = (PersonObject)XmlToObject(sb.ToString(), typeof(PersonObject));
Here is the method to convert the XML to the PersonObject:
private object XmlToObject(string XmlToConvert, Type DestinationType)
{
XmlSerializer serializer = new XmlSerializer(DestinationType);
StringReader stringReader = new StringReader(XmlToConvert);
XmlTextReader xmlReader = new XmlTextReader(stringReader);
object returnObject = serializer.Deserialize(xmlReader);
xmlReader.Close();
stringReader.Close();
return returnObject;
}
It is just a few lines of code. Very simple.
You will notice the PersonObject does not contain any XML attributes for basic use.