Dom4j操作xml文件实现简单增删改查
引入依赖
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
准备一个xml文件 book.xml
<books>
<book author="天蚕土豆">
<name>斗破苍穹</name>
<price>86</price>
</book>
<book author="萧潜">
<name>缥缈之旅</name>
<price>92</price>
</book>
<book author="萧鼎">
<name>诛仙</name>
<price>98</price>
</book>
<book author="天下霸唱">
<name>鬼吹灯</name>
<price>124</price>
</book>
<book author="辰东">
<name>神墓</name>
<price>128</price>
</book>
</books>
测试
@Test
void contextLoads() {
String fileName = "D:\\IDEA\\xmlTest\\src\\main\\resources\\books.xml";
try {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(fileName);
Element rootElement = document.getRootElement();
Element book1 = rootElement.addElement("book");
book1.addAttribute("author", "江南");
Element name1 = book1.addElement("name");
name1.addText("龙族");
Element price1 = book1.addElement("price");
price1.addText("199");
List<Element> elements2 = rootElement.elements();
Element book2 = elements2.get(2);
book2.addAttribute("author","爱潜水的乌贼");
Element name2 = book2.element("name");
name2.setText("诡秘之主");
Element price2 = book2.element("price");
price2.setText("300");
Element book3=(Element) rootElement.elements().get(0);
Attribute idAttr=book3.attribute("author");
idAttr.detach();
book3.detach();
List<Element> elements = rootElement.elements();
for (Element book : elements) {
String author = book.attributeValue("author");
String name = book.element("name").getText();
String price = book.element("price").getText();
System.out.println(name + " " + author + " " + price);
}
FileOutputStream out = new FileOutputStream(fileName);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(out, format);
writer.write(document);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
结果
控制台
缥缈之旅 萧潜 92
诡秘之主 爱潜水的乌贼 300
鬼吹灯 天下霸唱 124
神墓 辰东 128
龙族 江南 199
xml文件
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book author="萧潜">
<name>缥缈之旅</name>
<price>92</price>
</book>
<book author="爱潜水的乌贼">
<name>诡秘之主</name>
<price>300</price>
</book>
<book author="天下霸唱">
<name>鬼吹灯</name>
<price>124</price>
</book>
<book author="辰东">
<name>神墓</name>
<price>128</price>
</book>
<book author="江南">
<name>龙族</name>
<price>199</price>
</book>
</books>