据悉dom4j在xml解析方面是性能最好的,hibernate等框架都使用它作为解析的工具
写了简单的dom4j的使用的demo,以备回忆,有些是dom4j的文挡里例子改编的
使用dom4j解析下面的xml文件
Parse.java
使用dom4j来将属性写入xml
使用dom4j写入到author.xml文件的内容
写了简单的dom4j的使用的demo,以备回忆,有些是dom4j的文挡里例子改编的
使用dom4j解析下面的xml文件
<?xml version="1.0" encoding="GB2312"?>
<?xml-stylesheet type="text/xsl" href="students.xsl"?>
<students>
<student sn="01">
<name>张三</name>
<age>18</age>
</student>
<student sn="02">
<name>李四</name>
<age>20</age>
</student>
</students>
Parse.java
import java.io.File;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.ProcessingInstruction;
import org.dom4j.VisitorSupport;
import org.dom4j.io.SAXReader;
public class Parse {
public static void main(String[] args) {
SAXReader reader = new SAXReader();
File file = new File("src/students.xml");
try {
Document doc = reader.read(file);
doc.accept(new MyVistor());
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static class MyVistor extends VisitorSupport {
public void visit(Attribute node) {
System.out.println("Attibute:---" + node.getName() + "="
+ node.getValue());
}
public void visit(Element node) {
if (node.isTextOnly()) {
System.out.println("Element:---" + node.getName() + "="
+ node.getText());
}else{
System.out.println("--------" + node.getName() + "-------");
}
}
@Override
public void visit(ProcessingInstruction node) {
// TODO Auto-generated method stub
System.out.println("PI:"+node.getTarget()+" "+node.getText());
}
}
}
使用dom4j来将属性写入xml
import java.io.FileWriter;
import java.io.IOException;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class DWriter {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
XMLWriter writer = new XMLWriter(new FileWriter("src/author.xml"));
Document doc = createDoc();
writer.write(doc);
writer.close();
// Pretty print the document to System.out
// 設置了打印的格式,将读出到控制台的格式进行美化
OutputFormat format = OutputFormat.createPrettyPrint();
writer = new XMLWriter(System.out, format);
writer.write(doc);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Document createDoc() {
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("root");
Element author1 = root.addElement("author").addAttribute("name",
"James").addAttribute("location", "UK")
.addText("Jame Strachan");
Element author2 = root.addElement("author").addAttribute("name", "Bob")
.addAttribute("location", "US").addText("Bob McWrirter");
return doc;
}
}
使用dom4j写入到author.xml文件的内容
<?xml version="1.0" encoding="UTF-8"?>
<root><author name="James" location="UK">Jame Strachan</author><author name="Bob" location="US">Bob McWrirter</author></root>