API常用后台解析XML,JOSN数据的两种方式(XML)

     private XmlDocument Getlogistics(string UserID, string LogisticsID)
        {
            string url = string.Format("https://secure.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML=<?xml version='1.0' encoding='UTF-8' ?><TrackRequest USERID='{0}'><TrackID ID='{1} '></TrackID></TrackRequest>", UserID, LogisticsID);
            HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(url);
            HttpWReq.Method = "Get";
            HttpWReq.ContentType = "text/xml";
            HttpWReq.Timeout = 1200;
            HttpWReq.ReadWriteTimeout = 12000; //12秒链接不成功就中断
            HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
            var xmlContent = string.Empty;
            //将返回的结果读入流
            using (StreamReader sw = new StreamReader(HttpWResp.GetResponseStream()))
            {
                xmlContent = sw.ReadToEnd(); //将流从头到尾读完转换成字符串
                sw.Close();//关闭流读取
            }
            XmlDocument doc = new XmlDocument();//新建一个XML文档
            doc.LoadXml(xmlContent);//将字符串转换成XML文档
            return doc;

        }

 

这个是一个USPS快递的物流信息查询的API的封装方法,首先解析XML数据 务必生成XML文档

  //创建LIST集合
            List<string> xx = new List<string>();
            //解析XML
            XmlDocument xml = Getlogistics("XXXXXXX", "XXXXXXXXXXXX");
            //查询XML中TrackInfo节点
            XmlNodeList x = xml.GetElementsByTagName("TrackInfo");
            //循环遍历此节点
            foreach (XmlNode xz in x)
            {
                //获取此节点下的子节点
                XmlNodeList itemnodes = xz.ChildNodes;
                //遍历子节点
                foreach (XmlNode a in itemnodes)
                {
                    //判断子节点名称是否是TrackDetail
                    if (a.Name.Equals("TrackDetail"))
                    {
                        //将其添加在List中
                        xx.Add(a.InnerText);
                    }
                }
            }
            //最终所有的返回信息都存入了LIST集合中
            List<string> end = xx;

XML 解析数据基本上就是这个样子,还是很简单的 。不积跬步无以至千里~不积小流无以成江河~

posted @ 2018-04-23 09:48  爱好学习的菜鸡码农  阅读(1270)  评论(0编辑  收藏  举报