1
private void saveToXmlFile(ProcessInfo[] infos)
2
{
3
if (dom == null)
4
{
5
loadProcessInfo(true);
6
}
7
XMLWriter writer = null;
8
try
9
{
10
OutputFormat format = OutputFormat.createPrettyPrint();
11
writer = new XMLWriter(new FileWriter(filepath), format);
12
if (dom != null)
13
{
14
dom.clearContent();
15
}
16
dom = DocumentHelper.createDocument();
17
dom.setXMLEncoding("utf-8");
18
19
Element root = dom.addElement("processes");
20
for (int i = 0; i < infos.length; i++)
21
{
22
info2Element(root, infos[i]);
23
}
24
25
writer.write(dom);
26
writer.flush();
27
}
28
catch (IOException e)
29
{
30
log.error("存储XML文件出错", e);
31
}
32
finally
33
{
34
if (writer != null)
35
{
36
try
37
{
38
writer.close();
39
}
40
catch (IOException e)
41
{
42
// TODO Auto-generated catch block
43
e.printStackTrace();
44
}
45
}
46
}
47
48
49
}
创建xml 的主要类 DocumentHelper
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

见Line:16
dom = DocumentHelper.createDocument();
dom.setXMLEncoding("utf-8");
创建Document对象并设置编码
写入文件的主要类XMLWriter
格式化xml的辅助类OutputFormat
其创建过程参见Line 10
OutputFormat format = OutputFormat.createPrettyPrint();
writer = new XMLWriter(new FileWriter(filepath), format);
然后Document创建根Element
info2Element()的方法则是将对象转换到Element结构中去。
格式化的主要功臣就是 OutputFormat 相应的还有createCompactFormat() 创建压缩的xml文件,删去了所有的换行等无用的字符。createPrettyPrint() 则是生成格式化的xml 代码,让看起来好读一点。