具體代碼如下:
1
import java.io.FileNotFoundException;
2
import java.io.FileOutputStream;
3
import java.io.IOException;
4
5
import org.jdom.Document;
6
import org.jdom.Element;
7
import org.jdom.output.XMLOutputter;
8
9
10
public class XMLWriter {
11
/*
12
* 要輸出的文件格式為:
13
* <books>
14
* <book>
15
* <name>蝸居</name>
16
* <price>30.00</price>
17
* </book>
18
* <book>
19
* <name>和空姐同居的日子</name>
20
* <price>25.00</price>
21
* </book>
22
* <books>
23
*利用JDOM對(duì)XML文件 進(jìn)行寫操作,主要按以下步驟:
24
*1.創(chuàng)建根元素
25
*2.創(chuàng)建元素對(duì)象,利用addContent()方法為元素添加子元素或者文本值
26
*3.創(chuàng)建Document對(duì)象
27
*4.創(chuàng)建XMLOutputter對(duì)象,利用output()方法創(chuàng)建xml文件.
28
*/
29
public static void main(String[] args) throws Exception {
30
31
Element rootE = new Element("books");//創(chuàng)建根元素
32
Element e1 = new Element("book");
33
Element ename1 = new Element("name").addContent("蝸居");
34
Element eprice1 = new Element("price").addContent("30.00");
35
e1.addContent(ename1).addContent(eprice1);//添加子元素
36
Element e2 = new Element("book");
37
Element ename2 = new Element("name").addContent("和空姐同居的日子");
38
Element eprice2 = new Element("price").addContent("25.00");
39
e2.addContent(ename2).addContent(eprice2);
40
rootE.addContent(e1).addContent(e2);
41
Document d = new Document(rootE);//根據(jù)根元素創(chuàng)建Document,以便后續(xù)用
42
XMLOutputter xop = new XMLOutputter();//用來(lái)創(chuàng)建xml文件,輸出xml元素的
43
xop.output(d, new FileOutputStream("C:/Documents and Settings/Administrator/桌面/book.xml"));
44
}
45
46
}

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
