JAVA解析Xml实例

/** * 解析xml返回装有game集合的集合(三个游戏下载列表); * * @param path * 文件路径 * @return ArrayList<ArrayList<XML_GameListData>> game集合的集合 */ public ArrayList<ArrayList<XML_GameListData>> getGameArryLists(String path) throws TimeoutException { Util.printLog("==big arr game list==", "" + path); // 装arrlist的arraylist ArrayList<ArrayList<XML_GameListData>> bigarr = new ArrayList<ArrayList<XML_GameListData>>(); // 装game对象的arraylisyt ArrayList<XML_GameListData> 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); // 根节点为<list>节点 Element root = (Element) doc.getDocumentElement(); if (root == null || root.getNodeType() != Node.ELEMENT_NODE) { return null; } // 得到根节点下一层所有节点(包括<vouchlist><netlist>两个节点) 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文件为:

 <list><vouchlist><game id="4" type="1" ishot="1" name="愤怒的小鸟0"/><game id="2" type="1" ishot="1" name="愤怒的小鸟1"/><game id="3" type="1" ishot="1" name="愤怒的小鸟2"/><game id="6" type="1" ishot="1" name="五子棋"/><game id="7" type="1" ishot="1" name="愤怒的小鸟3"/><game id="8" type="1" ishot="1" name="愤怒的小鸟10"/></vouchlist><netlist><game id="4" type="1" ishot="1" name="愤怒的小鸟4"/><game id="2" type="1" ishot="1" name="愤怒的小鸟9"/><game id="3" type="1" ishot="0" name="愤怒的小鸟5"/><game id="6" type="1" ishot="1" name="愤怒的小鸟8"/><game id="7" type="1" ishot="1" name="愤怒的小鸟6"/><game id="8" type="1" ishot="1" name="愤怒的小鸟7"/></netlist><locallist/></list>  

 

 

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