java调用dom4j读写xml文件
程序员文章站
2022-05-29 12:17:03
...
java调用dom4j读写xml文件
maven引入dom4j
<!--xml读写-->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>${dom4j.version}</version>
</dependency>
xml文件
<?xml version="1.0" encoding="UTF-8"?>
<tables>
<table>
<prefix>01111</prefix>
<tablename>TABLE1</tablename>
</table>
<table>
<prefix>01112</prefix>
<tablename>TABLE2</tablename>
</table>
<table>
<prefix>13221</prefix>
<tablename>TABLE3</tablename>
</table>
</tables>
读取
// 获得File对象
File file = classPathResource.getFile();
SAXReader reader = new SAXReader();
Document doc = reader.read(file);
// 获取根节点
Element root = doc.getRootElement();
// 在根节点下循环table元素
Iterator i = root.elementIterator("table");
Element element;
while (i.hasNext()) {
element = (Element) i.next();
System.out.printlin(element.elementText("prefix"));
System.out.printlin(element.elementText("tablename"));
}
写入
ClassPathResource classPathResource = new ClassPathResource("valid_station.xml");
// 获得File对象,当然也可以获取输入流对象
File file = classPathResource.getFile();
SAXReader reader = new SAXReader();
Document document = reader.read(file);
//创建根元素
Element root = document.getRootElement();
//添加子节点1和设置属性
Element tableElem = root.addElement("table");
Element prefixElem = tableElem.addElement("prefix");
Element tablenameElem = tableElem.addElement("tablename");
prefixElem.addText("4321");
tablenameElem.addText("TABLE4");
// 输出流
FileOutputStream out = new FileOutputStream(file);
OutputFormat format = OutputFormat.createPrettyPrint();//标准化布局,适合查看时显示。
format.setEncoding("utf-8");//指定文件格式
// 输出到流
XMLWriter writer = new XMLWriter(out,format);
writer.write(document);
writer.close();