您的位置:首页 > 其它

读写XML(1)-关于Dom4j 生成xml文件,以及格式化的xml文件的样例

2008-07-21 11:23 447 查看
项目中遇到了读写xml文件的问题,下面贴上代码再逐一解释

1private 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

见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 代码,让看起来好读一点。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: