获取文件路径方法:
获取的文件默认在target目录下的classes中。
String fileName = 类名.class.getClassLoader().getResource("文件名").getPath();
使用的xml文档内容:
<?xml version="1.0" encoding="utf-8"?>
<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>
配置maven环境:
在pom文件中加入以下代码
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
(也可以自己去maven中找想要的版本)
读取xml文档转为dom4j的document对象:(解析xml使用)
/**
* 读取xml文件转为document对象
* @param file
* @return
* @throws DocumentException
*/
public static Document parse(File file) throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(file);
return document;
}
解析xml:(返回对象为List<Element>,为了方便创建文档使用)
解析xml文件代码:
/**
* 解析xml文档
* @param file
* @throws DocumentException
*/
public static List<Element> resolve(File file) throws DocumentException {
Document document = parse(file);
//获取根元素
Element rootElement = document.getRootElement();
//获取根元素的对象
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);
}
return elements;
}
创建xml文档并写入文件:
创建xml文档代码:
/**
* 创建xml文档
* @return
*/
public static Document createDocument(List<Element> list) {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");
for(Element book : list) {
String author = book.attributeValue("author");
String name = book.element("name").getText();
String price = book.element("price").getText();
root.addElement("book").addAttribute("name", name).addAttribute("price", price).addAttribute("author", author);
}
return document;
}
写入文件中:
/**
* 将创建的xml文档写入文件中
* @param document
* @throws IOException
*/
public static void write(Document document) throws IOException {
XMLWriter writer = new XMLWriter(
new FileWriter( "路径+文件名" )
);
writer.write( document );
writer.close();
}
最后附上dom4j的github使用指南,有需要别的功能的童鞋可以前往学习。