
正文
JavaWeb_使用dom4j解析、生成XML文件
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
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"

<?xml version="1.0" encoding="UTF-8"?>
<goodlist>
<good>
<price>12</price>
<name>香蕉</name>
<place>广州</place>
</good>
<good>
<price>39</price>
<name>苹果</name>
<place>北京</place>
</good>
<good>
<price>33</price>
<name>芒果</name>
<place>深圳</place>
</good>
</goodlist>
NewFile.xml
ParseXML解析NewFile.xml中的Dom元素

package Duoxiancheng;
import java.util.Iterator;import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;public class ParseXML {
public static void main(String[] args) throws Exception{
SAXReader reader = new SAXReader();
//获得xml文件路径
Document document = reader.read("src/NewFile.xml");
//获得根节点名
Element root = document.getRootElement();
System.out.println(root.getName());
//获取子元素
Iterator<Element> 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<Attribute> 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文件

package Duoxiancheng;import java.io.FileWriter;
import java.io.IOException;import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;public class CreateXML {
public static void main(String[] args) throws IOException {
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






