XML是一种可扩展标记语言
下面是一个完整的XML文件(也是下文介绍读写XML的样本):
一、写XML
本文介绍两种方式:使用DOM开发包来写XML文件和用String对象的方式
将Poem类作为数据源,提供需要转换成XML的内容:
[java]
copy
XML是一种可扩展标记语言
下面是一个完整的XML文件(也是下文介绍读写XML的样本):
一、写XML
本文介绍两种方式:使用DOM开发包来写XML文件和用String对象的方式
将Poem类作为数据源,提供需要转换成XML的内容:
1、用DOM写XML文件
流程:
(1)创建一个空的Document对象(最顶层的DOM对象,包含了创建XML所需要的其他一切)。
(2)创建元素和属性,把元素和属性加到Document对象中。
(3)把Document对象的内容转换成String对象。
(4)把String对象写到目标文件里去。
2、用String写XML文件
这种方法就比较简单,就是直接用字符串把整个XML文件描述出来,然后保存文件。
二、读取XML文件
两种方式:用DOM读取XML文件和用SAX方式。一般DOM处理内容比较小的XML文件,而SAX可以处理任意大小的XML文件。
1、用DOM读取XML文件
2、用SAX读取XML文件
SAX是使用ContentHandler接口来公开解析事件,而且SAX包提供了一个默认实现类DefaultHandler,它的默认行为就是什么都不做。下面就通过XMLToConsoleHandler类来覆盖其中的一些方法,来捕获XML文件的内容。