這裏主要是解析通常經常使用的三級,更多級數能夠寫死,一層一層的累加,也能夠寫個靈活的方法來判斷級數在解析。例子適合才接觸的新人。html
解析的xml:java
<?xml version="1.0" encoding="gbk"?> <ROWDATA> <ROW> <a>1111</a> <b>2222</b> <c>3333</c> <d>4444</d> </ROW> <ROW> <a>aaaa</a> <b>bbbb</b> <c>cccc</c> <d>dddd</d> </ROW> </ROWDATA>
PaseXml類:
dom
package com.cn; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * 解析三級xml * */ public class PaseXml { public List<Map<String, String>> pXml(String fileName) { Map<String, String> map = null; List<Map<String, String>> list = new ArrayList<Map<String, String>>(); SAXReader reader = new SAXReader(); try { Document document = reader.read(fileName); Element root = document.getRootElement(); Iterator<?> it = root.elementIterator(); while (it.hasNext()) { map = new HashMap<String, String>(); // ROW節點 Element e = (Element) it.next(); Iterator<?> its = e.elementIterator(); while (its.hasNext()) { Element el = (Element) its.next(); // xml的鍵值放入map裏面 map.put(el.getName(), el.getText()); } list.add(map); } } catch (DocumentException e1) { e1.printStackTrace(); } return list; } }
main類:code
public static void main(String[] args) { PaseXml px = new PaseXml(); String fileName = "D:/xmlfile/test.xml"; // String fileName = "D:/xmlfile/HOSPITAL.xml"; List<Map<String, String>> list = px.pXml(fileName); Iterator<?> it = list.iterator(); while (it.hasNext()) { Map<String, String> map = (Map<String, String>) it.next(); Iterator<?> itm = map.entrySet().iterator(); while (itm.hasNext()) { Map.Entry entry = (Map.Entry) itm.next(); Object key = entry.getKey(); Object value = entry.getValue(); System.out.println(key + ":" + value); } System.out.println("----------------------------------"); } }
d:4444
b:2222
c:3333
a:1111
----------------------------------
d:dddd
b:bbbb
c:cccc
a:aaaa
----------------------------------
xml