方法不在多,能用就好。
我采用的是dom4j
1<dependency> 2 <groupId>dom4j</groupId> 3 <artifactId>dom4j</artifactId> 4 <version>1.6.1</version> 5 </dependency>
读取的文件内容如下:
1<?xml version="1.0" encoding="UTF-8"?> 2<users> 3 <module id="1"> 4 <user index="1"> 5 <name>tom</name> 6 <password>12345</password> 7 <date>20150526</date> 8 </user> 9 <user index="2"> 10 <name>jack</name> 11 <password>5%</password> 12 <date>20150526</date> 13 </user> 14 <user index="3"> 15 <name>john</name> 16 <password>5%</password> 17 <date>20150526</date> 18 </user> 19 </module> 20</users>
读取思路是:
1. 创建一个SAXReader实例;
2. 创建一个文件读取BufferedReader实例;
3. 创建一个Document实例读取BufferedReader;
4. 获取xml文件的根节点;
5. 获取根节点的子节点;
6. 遍历子节点,获取节点名用getName(),获取节点的值用getText(),获取属性值用attributeValue(String)
获取根节点的代码如下:
1public static List<Element> readXml(String FilePath){ 2 BufferedReader in = null; 3 List<Element> elementlist = null; 4 Document doc = null; 5 6 SAXReader reader = new SAXReader(); 7 try { 8 in = new BufferedReader(new FileReader(FilePath)); 9 } catch (FileNotFoundException e) { 10 // TODO Auto-generated catch block 11 e.printStackTrace(); 12 } 13 try { 14 doc = reader.read(in); 15 } catch (DocumentException e) { 16 // TODO Auto-generated catch block 17 e.printStackTrace(); 18 } 19 20 Element root = doc.getRootElement(); 21 elementlist = root.elements(); 22 23 return elementlist; 24 25 }
遍历子节点, 读取用户名和密码的代码如下:
1@SuppressWarnings("unchecked") 2 public List<HashMap<String, String>> readUserDotXML(String path, String module_id){ 3 List<HashMap<String, String>> users = new ArrayList<HashMap<String, String>>(); 4 String rootPath = path; 5 List<Element> list = ReadXML.readXml(rootPath); 6 if (list != null) { 7 for (Element ele : list) { 8 String index = ele.attributeValue("id"); 9 if(module_id.equals(index)){ 10 List<Element> userList = ele.elements(); 11 if(userList != null && userList.size()>0){ 12 for (Element user : userList) { 13 HashMap<String,String> hashMap = new HashMap<String, String>(); 14 Element name = user.element("name"); 15 Element password = user.element("password"); 16 String nameValue = name.getText(); 17 String passwordValue = password.getText(); 18 hashMap.put("name", nameValue); 19 hashMap.put("password", passwordValue); 20 users.add(hashMap); 21 } 22 } 23 24 break; 25 } 26 } 27 } 28 29 return users; 30 31 }
main函数调用方法如下:
1List<HashMap<String, String>> resultlist= readxml.readUserDotXML("e:/testXML.xml","1"); 2 3for (HashMap<String, String> hashMap : resultlist) { 4 System.out.println(hashMap.get("name")); 5 System.out.println(hashMap.get("password")); 6}
使用java总感觉没python那么干脆,这里多几步,那里多几步的。下次对python也总结一下xml读取