需求
导入依赖
<dependencies><!-- dom4j --><dependency><groupId>dom4j</groupId><artifactId>dom4j</artifactId><version>1.6.1</version></dependency>
</dependencies>
代码
- SAXReader saxReader = new SAXReader(); 获取读取器
- Document document = saxReader.read(file); 获取文档对象
- Element rootElement = document.getRootElement(); 获取文档根元素
- List elements = rootElement.elements(); 获取根元素下面的子元素
//1. 定义一个集合
List<Order> orderList = new ArrayList<>();//2. 获取xml
SAXReader saxReader = new SAXReader();
//3. 获取文件对象 获取同一目录下的order.xml文件
File file = new File("demo/src/main/java/com/ruoyi/demo1/order.xml");
if (!file.exists()) {System.out.println("文件不存在");return;
}
//4. 解析xml
try{// 5. 获取Document对象Document document = saxReader.read(file);// 6. 获取根节点Element rootElement = document.getRootElement();// 7. 获取根节点下的所有子节点List<Element> elements = rootElement.elements();// 8. 遍历子节点for (Element element : elements) {// 9. 获取子节点的属性值int id = Integer.parseInt(element.attributeValue("id"));String name = element.elementText("name");DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");LocalDateTime time = LocalDateTime.parse(element.elementText("time"), formatter);double price = Double.parseDouble(element.elementText("price"));// 10. 创建Order对象Order order = new Order(id, name, time, price);// 11. 添加到集合中orderList.add(order);}}catch (Exception e){e.printStackTrace();
}// 12. 按照时间排序
ArrayList<Order> timeDesc = orderList.stream().sorted((o1, o2) -> o1.getTime().compareTo(o2.getTime())).collect(Collectors.toCollection(ArrayList::new));
// 13. 输出
timeDesc.forEach(System.out::println);// 使用stream流获取价格排序第低的订单
List<Order> priceDesc = orderList.stream().sorted((o1, o2) -> Double.compare(o1.getPrice(), o2.getPrice())).limit(1).collect(Collectors.toList());
System.out.println("价格最低的订单是:" + priceDesc.get(0));