花开有时

花开有时,花落有时,来有时,去有时。不撕扯,只关切;不纪念,只牵挂;不感动,只明白;不寻找,只记得。
随笔 - 24, 文章 - 0, 评论 - 54, 引用 - 0
数据加载中……

用Groovy读XML文件。

Groovy提供了更简单的方法进行XML文件的读取。

下面是要读取的XML文件pla.xml

<plan>

<week capacity="8">

<task done="2" total="2" title="read XML chapter"/>

<task done="3" total="3" title="try some reporting"/>

<task done="1" total="2" title="use in current project"/>

</week>

<week capacity="8">

<task done="0" total="1" title="re-read DB chapter"/>

<task done="0" total="3" title="use DB/XML combination"/>

</week>

</plan>

下面是代码:

def node = new XmlParser().parse(new File('data/plan.xml'))

def path = new XmlSlurper().parse(new File('data/plan.xml'))

assert 'plan' == node.name()

assert 'plan' == path.name()

assert 2 == node.children().size()

assert 2 == path.children().size()

assert 5 == node.week.task.size()

assert 5 == path.week.task.size()

assert 6 == node.week.task.'@done'*.toInteger().sum()

assert path.week[1].task.every{ it.'@done' == '0' }

Groovy提供了两个类进行XML文件的读取:XmlParser类和XmlSlurper类。这两个类的功能基本差不多,但是读的方法不同。概要的说,XmlParser类需要的内存更大些,它需要把整个XML文件先读取到内存中,在按要求进行检索,适合小文件。XmlSlurper则是需要什么内容就读什么内容,可能速度慢些。具体区别与用法可参看《Groovy in Action》的443页。

posted on 2007-09-25 10:12 花开有时 阅读(1941) 评论(0)  编辑  收藏 所属分类: java


只有注册用户登录后才能发表评论。


网站导航: