1、读取xml格式的字符串
假设有一段下面的xml格式的字符串:
<xml>
<return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg> </xml> 定义类ClientResponseHandler.cspublic class ClientResponseHandler{ protected Hashtable xmlMap; /* 设置xml字符串 */ 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); } } /* 设置xml字符串 */ 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); } }}
调用:
rescontent = ""; //假设这里是一段xml格式的字符串ClientResponseHandler resHandler = new ClientResponseHandler();resHandler.setContent(rescontent);string return_code = resHandler.getMpParameter("return_code"); //return_code是xml节点名称,返回SUCCESS string return_msg = resHandler.getMpParameter("return_msg"); //return_code是xml节点名称,返回OK
2、从上下文(Context)读取xml文件流
假设上下文中(Context)包含一段xml的字符串文件流,同上面格式。
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);//这里与上面不同 XmlNode root = xmlDoc.SelectSingleNode("xml"); XmlNodeList xnl = root.ChildNodes; foreach (XmlNode xnf in xnl) { xmlMap.Add(xnf.Name, xnf.InnerText); } } } /* 获取参数值 */ public string getMpParameter(string parameter) { string s = (string)xmlMap[parameter]; return (null == s) ? "" : s; }}
调用:
ResponseHandler resHandler = new ResponseHandler(Context);//Context 是HttpContext string return_code = resHandler.getMpParameter("return_code"); //return_code是xml的节点,返回SUCCESSstring return_msg = resHandler.getMpParameter("return_msg"); //return_msg是xml的节点,返回OK