JAVA解析Xml实例

/** * 解析xml返回装有game集合的集合(三个游戏下载列表); * * @param path * 文件路径 * @return ArrayList> game集合的集合 */ public ArrayList> getGameArryLists(String path) throws TimeoutException { Util.printLog("==big arr game list==", "" + path); // 装arrlist的arraylist ArrayList> bigarr = new ArrayList>(); // 装game对象的arraylisyt ArrayList arr; domfac = DocumentBuilderFactory.newInstance();// 有值 try { dombuilder = domfac.newDocumentBuilder();// 有值 http = (HttpURLConnection) new URL(path).openConnection(); http.setConnectTimeout(10000); http.setReadTimeout(10000); http.setDoInput(true); http.setDoOutput(true); // 得到网络连接状态 nRC = http.getResponseCode(); if (nRC == HttpURLConnection.HTTP_OK) { is = http.getInputStream(); doc = dombuilder.parse(is); Util.printLog("=doc=", "==" + doc); // 根节点为节点 Element root = (Element) doc.getDocumentElement(); if (root == null || root.getNodeType() != Node.ELEMENT_NODE) { return null; } // 得到根节点下一层所有节点(包括两个节点) NodeList mainItems = root.getChildNodes(); if (mainItems != null) { // 循环读取xml文件中每个标签和下层标签 for (int i = 0; i < mainItems.getLength(); i++) { // 0为vouchlist节点,1为netlist节点; Node secondItems = mainItems.item(i); arr = new ArrayList(); // 获得itemlist下game标签的结合 NodeList gamelist = secondItems.getChildNodes(); if (gamelist != null) { for (int j = 0; j < gamelist.getLength(); j++) { // list下第i个节点下一层的第j个game节点 Node gameitem = gamelist.item(j); XML_GameListData gamedata = new XML_GameListData(); if (gameitem.getNodeType() == Node.ELEMENT_NODE) { gamedata.setId(gameitem.getAttributes() .getNamedItem("id").getNodeValue()); gamedata.setType(gameitem.getAttributes() .getNamedItem("type") .getNodeValue()); gamedata.setIsHot(gameitem.getAttributes() .getNamedItem("ishot") .getNodeValue()); gamedata.setName(gameitem.getAttributes() .getNamedItem("name") .getNodeValue()); } arr.add(gamedata); } } bigarr.add(arr); } } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } if (http != null) { http.disconnect(); } } catch (Exception e) { e.printStackTrace(); return null; } } return bigarr; }

解析xml文件为:

   

 

 

你可能感兴趣的:(JAVA,xml,java,exception,null,path,list)