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 i开发者_StackOverflow中文版t 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?
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
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;
}
精彩评论