方法不在多,能用就好。
我采用的是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读取