Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize XML Messages to Objects

I'm writing a client for a protocol that uses HTTP to transport XML messages. It is synchronous because I form an XML document that follows a DTD and send it to a gateway for the protocol via POST with the WebClient class and I get an XML response message from the remote server to indicate transaction state/message ID/etc.

Since I have the DTD, is it possible to create classes with it? There are a handful of possible responses for each type of "operation" my XML message is performing and having classes that could be hydrated by the returned server XML would be advantageous.

Once I have those classes, what are the basic steps to deserializing the XML message from the server into objects?

like image 687
Jeff LaFay Avatar asked Jul 06 '11 17:07

Jeff LaFay


2 Answers

Covert the DTD to XSD (not sure if this step is still required) :

Free DTD to XSD conversion utility?

Generate C# class from the XSD (command line tool, this is how I do it, not sure if there is a better way) :

http://quickstart.developerfusion.co.uk/quickstart/howto/doc/xmlserialization/XSDToCls.aspx

Serialize back to class from XML :

http://support.microsoft.com/kb/815813

like image 176
Eric H Avatar answered Sep 29 '22 10:09

Eric H


once you have the xml string, you can do something like this where T is your generic object.

public static T GetObjectFromXmlString<T>(string xml)
{
    T result = default(T);

    if (string.IsNullOrEmpty(xml))
        return result;

    using (StringReader sr = new StringReader(xml))
    {
        using (XmlTextReader xr = new XmlTextReader(sr))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            result = (T)serializer.Deserialize(xr);
        }                   
    }

    return result;
}
like image 27
coder net Avatar answered Sep 29 '22 09:09

coder net