標籤:name pytho array dom4j roo pass exception result rate
方法不在多,能用就好。
我採用的是dom4j
<dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency>
讀取的檔案內容如下:
<?xml version="1.0" encoding="UTF-8"?><users> <module id="1"> <user index="1"> <name>tom</name> <password>12345</password> <date>20150526</date> </user> <user index="2"> <name>jack</name> <password>5%</password> <date>20150526</date> </user> <user index="3"> <name>john</name> <password>5%</password> <date>20150526</date> </user> </module></users>
讀取思路是:
1. 建立一個SAXReader執行個體;
2. 建立一個檔案讀取BufferedReader執行個體;
3. 建立一個Document執行個體讀取BufferedReader;
4. 擷取xml檔案的根節點;
5. 擷取根節點的子節點;
6. 遍曆子節點,擷取節點名用getName(),擷取節點的值用getText(),擷取屬性值用attributeValue(String)
擷取根節點的代碼如下:
public static List<Element> readXml(String FilePath){ BufferedReader in = null; List<Element> elementlist = null; Document doc = null; SAXReader reader = new SAXReader(); try { in = new BufferedReader(new FileReader(FilePath)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { doc = reader.read(in); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } Element root = doc.getRootElement(); elementlist = root.elements(); return elementlist; }
遍曆子節點, 讀取使用者名稱和密碼的代碼如下:
@SuppressWarnings("unchecked") public List<HashMap<String, String>> readUserDotXML(String path, String module_id){ List<HashMap<String, String>> users = new ArrayList<HashMap<String, String>>(); String rootPath = path; List<Element> list = ReadXML.readXml(rootPath); if (list != null) { for (Element ele : list) { String index = ele.attributeValue("id"); if(module_id.equals(index)){ List<Element> userList = ele.elements(); if(userList != null && userList.size()>0){ for (Element user : userList) { HashMap<String,String> hashMap = new HashMap<String, String>(); Element name = user.element("name"); Element password = user.element("password"); String nameValue = name.getText(); String passwordValue = password.getText(); hashMap.put("name", nameValue); hashMap.put("password", passwordValue); users.add(hashMap); } } break; } } } return users; }
main函數調用方法如下:
List<HashMap<String, String>> resultlist= readxml.readUserDotXML("e:/testXML.xml","1");for (HashMap<String, String> hashMap : resultlist) { System.out.println(hashMap.get("name")); System.out.println(hashMap.get("password"));}
使用java總感覺沒python那麼乾脆,這裡多幾步,那裡多幾步的。下次對python也總結一下xml讀取
java讀取XML