需要导包:dom4j-1.6.1.jar jaxen-1.1-beta-6.jar
------读取---------
package com. atguigu.xml.dom4j;
import java. util.Iterator;
import java. util.List;
import org. dom4j.Document;
import org. dom4j.Element;
import org. dom4j.io.SAXReader;
public class Dom4jParse {
//①查找某一个节点 : 查找id 为007的学员的所有信息
public static void main(String[] args) throws Exception {
//1.获取解析器对象
SAXReader reader = new SAXReader ();
//2.获取Document 对象
Document document = reader.read( "XML/students.xml");
//3.获取XML 文档的根节点对象
Element rootElement = document .getRootElement ();
//4.获取所有的student 元素对象,并进行遍历
List <Element > stuList = rootElement.elements( "student");
Iterator <Element > iterator = stuList .iterator ();
while (iterator .hasNext ()) {
Element stuEle = iterator .next ();
//5.获取每一个student 元素对象的id属性值
String idStr = stuEle .attributeValue ("id");
//6.检测id 属性值是否等于 007
if("007" .equals (idStr )) {
//7.如果等于则获取name值和 age值
Element nameEle = stuEle .element ("name");
Element ageEle = stuEle .element ("age");
String nameStr = nameEle .getText ();
String ageStr = ageEle .getText ();
System .out .println ("name="+nameStr+"
age="+ageStr);
}
}
}
}
------写入-----
package com. atguigu.xml.dom4j;
import java. io.FileWriter;
import org. dom4j.Document;
import org. dom4j.Element;
import org. dom4j.io.OutputFormat ;
import org. dom4j.io.SAXReader;
import org. dom4j.io.XMLWriter;
public class Dom4jEdit {
//②添加某一个节点 :
"姓名:张三丰,id:武当 ,年龄:108
public static void main(String[] args) throws Exception {
//1.获取Document 对象
SAXReader reader = new SAXReader ();
Document document = reader.read( "XML/students.xml");
//2.构建并添加节点内容
/*
<student id=" 武当">
<name> 张三丰</name>
<age>108</age>
</student>
*/
//①获取根节点,在根节点下,添加 student元素<student></student>
//②在新student 中添加id属性 <student
id="武当"></student>
//③在新student 下面添加name元素 <student
id="武当"><name></name></student>
//④在新name 下添加文本<student
id="武当 "><name>张三丰</name></student>
//⑤在新student 下面添加age元素 <student
id="武当"><name> 张三丰</name><age></age></student>
//⑥在新age 下添加文本<student
id="武当 "><name>张三丰</name><age>108</age></student>
Element rootElement = document .getRootElement ();
rootElement
.addElement ("student")
.addAttribute ("id", " 武当")
.addElement ("name")
.addText ("张三丰 ")
.getParent ()
.addElement ("age")
.addText ("108");
//3.将更新的内容写入XML文档
//①获取XMlWriter 对象
//为了使XML 节点内容写入后保持较好的格式,可以传入一个格式对象
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter (new FileWriter("XML/studentsNewPretty.xml"), format);
//②将Document 对象写入
writer .write (document );
//③关闭XMlWriter 对象
writer .close ();
}
}