//http://www.dom4j.org官方网址
public class DOM4JTest {
public static void main(String[] args){
//创建文档
Document doc = DocumentHelper.createDocument();
//创建根元素
//Element root = DocumentHelper.createElement("students");
//把根元素加入到文档
//doc.setRootElement(root);
//这样不会清除处理指令
Element root = doc.addElement("students");
//创建三个Element对象,分别加入到各自的对象中
Element stu1 = root.addElement("student");
//设置属性
stu1.addAttribute("sn", "01");
Element name1 = stu1.addElement("name");
Element age1 = stu1.addElement("age");
//设置文本属性
name1.setText("张三");
age1.setText("18");
//创建三个Element对象,分别加入到各自的对象中
Element stu2 = root.addElement("student");
//设置属性
stu2.addAttribute("sn", "02");
Element name2 = stu2.addElement("name");
Element age2 = stu2.addElement("age");
//设置文本属性
name2.setText("李四");
age2.setText("28");
/**
//创建PrintWriter对象
PrintWriter pw = new PrintWriter(System.out);
try {
//文档写到这个PW指定地方
doc.write(pw);
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
*/
//创建OutputStream对象,设置格式和是否换行
OutputFormat opf = new OutputFormat(" ",true);
//设置编码
opf.setEncoding("utf-8");
try {
//XMLWriter xml = new XMLWriter(opf);
//输出到其它地方,要自己关闭
XMLWriter xml = new XMLWriter(new FileOutputStream("langhua.xml"), opf);
//用XMLWriter把doc对象写到对应的输出流FileOutputSteam
xml.write(doc);
//xml.close其实是关闭FileOutputStream
xml.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Visitor模式
public class VisitorDom4JTest {
//Visitor是接口,VisitorSupport是实现类,但是是空实现
//这样在使用的时候只用extends VisitorSupport类
//因为这样不用实现所有的方法
VisitorSupport vs = null;
public static void main(String[] args){
//创建一个SAXReader对象来读取XML文档
SAXReader sax = new SAXReader();
try {
//读取一个XML文档,返回一个Document对象
Document doc = sax.read(new File("students.xml"));
//应该是一个遍历,遍历这个doc中所有的Node
doc.accept(new MyVisitor());
} catch (DocumentException e) {
e.printStackTrace();
}
}
private static class MyVisitor extends VisitorSupport{
//遇到属性节点
public void visit(Attribute node) {
System.out.println("Attribute:"+node.getName()+"="+node.getValue());
}
//元素节点
public void visit(Element node) {
//看这个元素是否只包括文本信息
if(node.isTextOnly()){
System.out.println("Element:"+node.getName()+"="+node.getText());
}else{
System.out.println("Not only Element:"+node.getName());
}
}
}
}
Dom4J解析XML文档(读,写)
最新推荐文章于 2023-07-17 22:33:59 发布