用Groovy讀XML文件。
Groovy提供了更簡(jiǎn)單的方法進(jìn)行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提供了兩個(gè)類進(jìn)行XML文件的讀取:XmlParser類和XmlSlurper類。這兩個(gè)類的功能基本差不多,但是讀的方法不同。概要的說(shuō),XmlParser類需要的內(nèi)存更大些,它需要把整個(gè)XML文件先讀取到內(nèi)存中,在按要求進(jìn)行檢索,適合小文件。XmlSlurper則是需要什么內(nèi)容就讀什么內(nèi)容,可能速度慢些。具體區(qū)別與用法可參看《Groovy in Action》的443頁(yè)。
posted on 2007-09-25 10:12 花開有時(shí) 閱讀(1962) 評(píng)論(0) 編輯 收藏 所屬分類: java