dom4j 官网
xml解析DOM文档对象模型(树形结构)
DOM方式解析:把xml文档加载到内存形成树形结构,可以进行增删改的操作
Learn
使用dom4j解析文件"NewFile.xml"
使用dom4j生成XML文件
添加jar包进Project中 百度云 传送门 密码:7c8x
1,解析根元素
2,解析有哪些子元素
3,解析一个元素又哪些属性
4,得到元素的文本内容
5,修改、添加、删除某个元素节点
6,修改、添加、删除某个属性
解析的时候可以做的事情
Gary->New->Folder 新建一个lib文件夹
Ctrl C+Ctrl V 将dom4j.jar包复制到lib文件夹中
dom4j.jar->Build Path->Add to Build Path
dom4j解析文件"NewFile.xml"
12
香蕉
广州
39
苹果
北京
33
芒果
深圳
NewFile.xml
ParseXML解析NewFile.xml中的Dom元素
packageDuoxiancheng;importjava.util.Iterator;importorg.dom4j.Attribute;importorg.dom4j.Document;importorg.dom4j.Element;importorg.dom4j.io.SAXReader;public classParseXML {public static void main(String[] args) throwsException{
SAXReader reader= newSAXReader();//获得xml文件路径
Document document = reader.read("src/NewFile.xml");//获得根节点名
Element root =document.getRootElement();
System.out.println(root.getName());//获取子元素
Iterator it =root.elementIterator();while(it.hasNext()) {
Element ele=it.next();//获取子元素为name中的文本值//存在good中没文本会抛出java.lang.NullPointerException空指针异常
if(ele.getName().equals("good")) {
Element name= ele.element("name");//if(name!=null)
System.out.println(name.getText());
}//获得子元素名
System.out.println(ele.getName());
Iterator attributes =ele.attributeIterator();while(attributes.hasNext()) {
Attribute ab=attributes.next();
System.out.println(ab.getName()+":"+ab.getValue());
}
}//xml :Element Attribute//函数方法输入.后查看
Element ele = null;//ele.elementIterator(); 遍历方法//ele.
Attribute ab= null;//ab.
}
}
ParseXML.class
输出:
goodlist
香蕉
good
苹果
good
芒果
good
dom4j生成XML文件
packageDuoxiancheng;importjava.io.FileWriter;importjava.io.IOException;importorg.dom4j.Document;importorg.dom4j.DocumentHelper;importorg.dom4j.Element;public classCreateXML {public static void main(String[] args) throwsIOException {
Document document=DocumentHelper.createDocument();
Element root= document.addElement("root");
Element author1= root.addElement("author")
.addAttribute("name","Gary")
.addAttribute("localtion", "China")
.addText("Hello Gary");//author1.addElement("添加子标签name")
Element author2= root.addElement("author")
.addAttribute("name","Bob")
.addAttribute("localtion", "US")
.addText("Hello Bob");//保存文件,运行后刷新一下工程
FileWriter out = new FileWriter("Gary.xml");
document.write(out);
out.close();
}
}
CreateXML.class