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頁。