Reads xml data from strings and contexts in xml format.
1. Read strings in xml format
Suppose there is a string in the following xml format:
<Xml>
<Return_code> <! [CDATA [SUCCESS]> </return_code>
<Return_msg> <! [CDATA [OK]> </return_msg>
</Xml>
ClientResponseHandler. cs
Public class ClientResponseHandler {protected Hashtable xmlMap;/* set the xml string */public virtual void setContent (string content) {this. content = content; XmlDocument xmlDoc = new XmlDocument (); xmlDoc. loadXml (content); XmlNode root = xmlDoc. selectSingleNode ("xml"); XmlNodeList xnl = root. childNodes; foreach (XmlNode xnf in xnl) {xmlMap. add (xnf. name, xnf. innerText) ;}}/* set the xml string */public virtual void setContent (string content) {this. content = content; XmlDocument xmlDoc = new XmlDocument (); xmlDoc. loadXml (content); XmlNode root = xmlDoc. selectSingleNode ("xml"); XmlNodeList xnl = root. childNodes; foreach (XmlNode xnf in xnl) {xmlMap. add (xnf. name, xnf. innerText );}}}
Call:
Rescontent = ""; // assume that a string in xml format is ClientResponseHandler resHandler = new ClientResponseHandler (); resHandler. setContent (rescontent); string return_code = resHandler. getMpParameter ("return_code"); // return_code is the xml node name, and SUCCESS is returned.
String return_msg = resHandler. getMpParameter ("return_msg"); // return_code is the name of the xml node, and OK is returned.
2. Read xml file streams from Context
Assume that the Context contains a string file stream of xml, in the same format as above.
Public class ResponseHandler {private Hashtable xmlMap; public ResponseHandler (HttpContext httpContext) {if (this. httpContext. request. inputStream. length> 0) {XmlDocument xmlDoc = new XmlDocument (); xmlDoc. load (this. httpContext. request. inputStream); // different from the above XmlNode root = xmlDoc. selectSingleNode ("xml"); XmlNodeList xnl = root. childNodes; foreach (XmlNode xnf in xnl) {xmlMap. add (xnf. name, xnf. in NerText) ;}}/ * Get the parameter value */public string getMpParameter (string parameter) {string s = (string) xmlMap [parameter]; return (null = s )? "": S ;}}
Call:
ResponseHandler resHandler = new ResponseHandler (Context); // The Context is HttpContext string return_code = resHandler. getMpParameter ("return_code"); // The return_code is an xml node, and SUCCESSstring return_msg = resHandler is returned. getMpParameter ("return_msg"); // return_msg is an xml node, and OK is returned.