标签:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 使用工厂来实例化一个构造Document的对象 DocumentBuilder builder = factory.newDocumentBuilder(); // 利用DocumentBuilder来构造一个Document对象 Document document = builder.parse(filename); // 获取Document文档的根节点对象 Element root = document.getDocumentElement(); // 通过根节点,获取到根节点下面的所有二级子节点 NodeList nodeList = root.getChildNodes(); // 遍历子节点,获取内部的每一个节点 for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); // 获取每个末端阶段的文本值和节点名称,将其存入到Map对象中 map.put(item.getNodeName(), item.getTextContent()); list.add(map); }
1 // 实例化一个xml pull解析的工厂 2 XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 3 // 实例化一个xml pull解析对象 4 XmlPullParser pullParser = factory.newPullParser(); 5 // 将xml文件作为流传入到inputstream 6 BufferedInputStream bis = new BufferedInputStream( 7 new FileInputStream("customers.xml")); 8 9 // xml解析对象接收输入流对象 10 pullParser.setInput(bis, "utf-8"); 11 12 int event = pullParser.getEventType(); 13 List<Map<String, Object>> list = null; 14 Map<String, Object> map = null; 15 16 while (event != XmlPullParser.END_DOCUMENT) { 17 switch (event) { 18 case XmlPullParser.START_DOCUMENT: 19 list = new ArrayList<>(); 20 break; 21 case XmlPullParser.START_TAG: 22 if ("customer".equals(pullParser.getName())) { 23 map = new HashMap<String, Object>(); 24 } 25 if (pullParser.getName().equals("name")) { 26 map.put("name", pullParser.nextText()); 27 } 28 if (pullParser.getName().equals("tel")) { 29 map.put("tel", pullParser.nextText()); 30 } 31 // if (pullParser.getName().equals("email")) { 32 // map.put("email", pullParser.nextText()); 33 // } 34 break; 35 case XmlPullParser.END_TAG: 36 if (pullParser.getName().equals("customer")) { 37 list.add(map); 38 } 39 break; 40 } 41 event = pullParser.next(); 42 }
标签:
原文地址:http://www.cnblogs.com/weifengzz/p/5012096.html