加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

XML解析工具类

发布时间:2020-12-16 07:40:06 所属栏目:百科 来源:网络整理
导读:XML解析工具类的封装 之前在csdn上面写了关于xml文件的解析 ,那都是一些本地数据 ,今天 在开发的过程中涉及到 从服务器返回xml文件格式的数据 稍后会写一些关于http请求的封转 返回JSON格式的数据的博客 到时候和大家一起分享 希望大家更多的和我一起进行

XML解析工具类的封装

之前在csdn上面写了关于xml文件的解析 ,那都是一些本地数据 ,今天 在开发的过程中涉及到 从服务器返回xml文件格式的数据 稍后会写一些关于http请求的封转 返回JSON格式的数据的博客 到时候和大家一起分享 希望大家更多的和我一起进行讨论和学习。

主要实现的思路是:先发送http请求 拿到字符串类型的xml文件格式的数据 然后再转化成dom去解析 然后再去操作节点的数据

public class XMLParser { // constructor public XMLParser() { } /** * Getting XML from URL making HTTP request * * @param url * string * */ public String getXmlFromUrl(String url) { String xml = null; try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); xml = EntityUtils.toString(httpEntity,"utf-8"); } catch (Exception e) { e.printStackTrace(); } // return XML return xml; } /* * * * Getting XML DOM element * * @param XML string */ public Document getDomElement(String xml) { Document doc = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); doc = db.parse(is); } catch (ParserConfigurationException e) { Log.e("Error: ",e.getMessage()); return null; } catch (SAXException e) { Log.e("Error: ",e.getMessage()); return null; } catch (IOException e) { Log.e("Error: ",e.getMessage()); return null; } return doc; } /** * Getting node value * * @param elem * element */ public final String getElementValue(Node elem) { Node child; if (elem != null) { if (elem.hasChildNodes()) { for (child = elem.getFirstChild(); child != null; child = child .getNextSibling()) { if (child.getNodeType() == Node.TEXT_NODE) { return child.getNodeValue(); } } } } return ""; } /** * Getting node value * * @param Element * node * @param key * string * */ public String getValue(Element item,String str) { NodeList n = item.getElementsByTagName(str); return this.getElementValue(n.item(0)); }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读