读取XML内容

很多时候需要为程序设置全局变量或者经常需要修改的量,这时候放到XML配置文件里就很有必要了

需要用的的包 dom4j 下载地址
代码如下

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
import java.io.File;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class ReadXMLDemo {
public static void main(String[] args) throws Exception {
// 读取XML文件,获得document对象
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/test.xml"));
// 取得节点对象
Element root = document.getRootElement();// 取得根节点
Element books = root.element("Books"); // 取得该节点下 "Books" 子节点
Element book = books.element("Book");
System.out.println(book.getName() + book.getText()); // getName()获取该节点名字,getText()取得该节点内容
System.out.println(book.attribute("id").getText()); //book.attribute("id")获取该节点下属性为id的内容
// 遍历子节点下所有元素
List<Element> bookList = book.elements();
for (Element element : bookList) {
System.out.println(element.getName() + " :" + element.getText());
}
//遍历子节点下子节点所有元素
for (Iterator it = books.elementIterator(); it.hasNext();) {
Element element = (Element) it.next();
List<Element> booksList = element.elements();
for (Element element2 : booksList) {
System.out.println(element2.getName() + ": " + element2.getText());
}
}
}
}

XML文件如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="UTF-8"?>
<Info>
<Books>
<Book id="001">
<Name>Java</Name>
<Price>50.0</Price>
</Book>
<Book id="002">
<Name>Python</Name>
<Price>30.0</Price>
</Book>
</Books>
<Phones>
<Phone id="001">
<Name>三星S8</Name>
<Price>5588.0</Price>
</Phone>
</Phones>
</Info>