forked from wujun728/jun_java_plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestJDom.java
More file actions
95 lines (89 loc) · 3.02 KB
/
TestJDom.java
File metadata and controls
95 lines (89 loc) · 3.02 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.XMLOutputter;
/**
* JDom读写xml
* @author whwang
*/
public class TestJDom {
public static void main(String[] args) {
read();
write();
}
public static void read() {
try {
boolean validate = false;
SAXBuilder builder = new SAXBuilder(validate);
InputStream in = TestJDom.class.getClassLoader().getResourceAsStream("university.xml");
Document doc = builder.build(in);
// 获取根节点 <university>
Element root = doc.getRootElement();
readNode(root, "");
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public static void readNode(Element root, String prefix) {
if (root == null) return;
// 获取属性
List<Attribute> attrs = root.getAttributes();
if (attrs != null && attrs.size() > 0) {
System.err.print(prefix);
for (Attribute attr : attrs) {
System.err.print(attr.getValue() + " ");
}
System.err.println();
}
// 获取他的子节点
List<Element> childNodes = root.getChildren();
prefix += "\t";
for (Element e : childNodes) {
readNode(e, prefix);
}
}
public static void write() {
boolean validate = false;
try {
SAXBuilder builder = new SAXBuilder(validate);
InputStream in = TestJDom.class.getClassLoader().getResourceAsStream("university.xml");
Document doc = builder.build(in);
// 获取根节点 <university>
Element root = doc.getRootElement();
// 修改属性
root.setAttribute("name", "tsu");
// 删除
boolean isRemoved = root.removeChildren("college");
System.err.println(isRemoved);
// 新增
Element newCollege = new Element("college");
newCollege.setAttribute("name", "new_college");
Element newClass = new Element("class");
newClass.setAttribute("name", "ccccc");
newCollege.addContent(newClass);
root.addContent(newCollege);
XMLOutputter out = new XMLOutputter();
File file = new File("src/jdom-modify.xml");
if (file.exists()) {
file.delete();
}
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
out.output(doc, fos);
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}