1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
package
com.yitong.dom4j;
import
java.io.FileInputStream;
import
java.io.FileNotFoundException;
import
java.io.FileOutputStream;
import
java.io.IOException;
import
java.util.List;
import
org.dom4j.Document;
import
org.dom4j.DocumentException;
import
org.dom4j.DocumentHelper;
import
org.dom4j.Element;
import
org.dom4j.io.OutputFormat;
import
org.dom4j.io.SAXReader;
import
org.dom4j.io.XMLWriter;
/**
* dom4j 创建,解析xml
* @author tingiting123
*
*/
public
class
TestDom4j {
//dom4j创建xml
public
void
createXML()
throws
IOException{
// 第一种方式:创建文档,并创建根元素
// 创建文档:使用了一个Helper类
Document document = DocumentHelper.createDocument();
Element students = DocumentHelper.createElement(
"students"
);
// 创建根节点并添加进文档
document.setRootElement(students);
//将根节点添加到文档
//创建子节点下的根节点student
for
(
int
i =
0
;i<
5
;i++){
Element student = students.addElement(
"student"
);
student.addAttribute(
"id"
, (i+
1
)+
""
);
//设置根节点是属性id=1
Element name = student.addElement(
"name"
);
Element age = student.addElement(
"age"
);
name.setText(
"张三丰"
+(i+
1
));
age.setText(
"2"
+(i+
1
));
}
// 输出到文件,格式
OutputFormat format =
new
OutputFormat(
" "
,
true
);
// 设置缩进为4个空格,并且另起一行为true //输出格式
XMLWriter xmlWriter =
new
XMLWriter(
new
FileOutputStream(
"student.xml"
), format);
xmlWriter.write(document);
xmlWriter.close();
//方法也可以
}
//dom4j读取,解析xml
public
void
parseXML()
throws
FileNotFoundException, DocumentException{
SAXReader sr =
new
SAXReader();
Document doc = sr.read(
new
FileInputStream(
"student.xml"
));
Element students = doc.getRootElement();
List student = students.elements();
for
(
int
i=
0
;i<student.size();i++){
Element sonStu = (Element) student.get(i);
System.out.println(
"id= "
+sonStu.attributeValue(
"id"
));
List sonList = sonStu.elements();
for
(
int
j =
0
;j<sonList.size();j++){
Element sonElement = (Element)sonList.get(j);
String sonStr = sonElement.getTextTrim();
System.out.print(sonStr+
"\t"
);
}
System.out.println();
}
}
public
static
void
main(String[] args)
throws
Exception {
new
TestDom4j().createXML();//先创建xml
new
TestDom4j().parseXML(); //在解析xml
}
}
|
09-02