如何使用dom4j如何读写xml文件
程序员文章站
2022-03-03 16:59:36
...
读取XML文件
主要代码:
SAXReader reader = new SAXReader();
Document document = reader.read(xmlFile);
要读取的xml文件内容
<?xml version="1.0" encoding="UTF-8"?>
<person>
<name>Tom</name>
<age>11</age>
</person>
实现具体代码:
import java.io.File;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
public class ReadXML {
@Test
public void readXML(){
String path = ReadXML.class.getResource("/file/demo.xml").getPath();
File xmlFile = new File(path);
//创建读取器
SAXReader reader = new SAXReader();
try {
//从File中读取xml文档对象document
Document document = reader.read(xmlFile);
Element root = document.getRootElement();
String rootName = root.getName();
//获取根元素的子元素的迭代器
Iterator<Element> i = root.elementIterator();
System.out.println("根元素:<" + rootName + ">");
while(i.hasNext()){
Element e = i.next();
System.out.println("\t元素名:<" + e.getName() + ">,元素内容:" + e.getTextTrim());
}
//----------------获取节点下的某个子节点---------------------
Element element = root.element("name");
System.out.println(element.getName() + ":" + element.getText());
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
运行结果
根元素:<person>
元素名:<name>,元素内容:Tom
元素名:<age>,元素内容:11
name:Tom
操作Document和写入XML
主要代码:
Document document = DocumentHelper.createDocument();
XMLWriter writer = new XMLWriter(new FileOutputStream(file),format);
writer.write(document);
具体实现代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.junit.Test;
public class WriteXML {
@Test
public void write(){
//创建一个Document对象
Document document = DocumentHelper.createDocument();
//添加根节点
Element root = document.addElement("root");
Element ele = root.addElement("element1");
//添加属性的名称和值
ele.addAttribute("style", "simple");
//添加节点内容
ele.addText("内容");
try {
String path = WriteXML.class.getResource("/file").getPath();
File file = new File(path+"/out.xml");
//设置自动缩进的格式化类
OutputFormat format = OutputFormat.createPrettyPrint();
//写入输出流指定的文件中
XMLWriter writer = new XMLWriter(new FileOutputStream(file),format);
writer.write(document);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
得到的xml文档
<?xml version="1.0" encoding="UTF-8"?>
<root>
<element1 style="simple">内容</element1>
</root>