1.引两个包
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1-beta-11</version>
<exclusions>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
</exclusions>
</dependency>
2.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<emps>
<emp>
<id>1</id>
<name>张三</name>
<age>26</age>
<gender>男</gender>
<salary>3000</salary>
</emp>
<emp>
<id>2</id>
<name>李四</name>
<age>21</age>
<gender>女</gender>
<salary>2000</salary>
</emp>
<emp>
<id>3</id>
<name>王五</name>
<age>28</age>
<gender>女</gender>
<salary>6500</salary>
</emp>
<emp>
<id>4</id>
<name>赵六</name>
<age>28</age>
<gender>男</gender>
<salary>5500</salary>
</emp>
<emp>
<id>5</id>
<name>钱七</name>
<age>53</age>
<gender>男</gender>
<salary>12000</salary>
</emp>
</emps>
3.代码
public class XmlResolver {
public static void main(String[] args) throws DocumentException {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new File("D:\\workspace\\spingMVC\\src\\main\\java\\com\\chengh\\spingmvc\\test.xml"));
List<Element> list = document.selectNodes("/emps/emp");
List<User> userList = resolverUser(list);
userList.forEach(System.out::println);
}
public static List<User> resolverUser(List<Element> list){
List<User> userList = new ArrayList<>();
for (Element e : list){
User user = new User(e.selectSingleNode("id").getText(),
e.selectSingleNode("name").getText(),
Integer.parseInt(e.selectSingleNode("age").getText()),
e.selectSingleNode("gender").getText(),
Integer.parseInt(e.selectSingleNode("salary").getText()));
userList.add(user);
}
return userList;
}
}
4解析结果
|