一、解析XML
groovy简化了java解析XML(点此查看)的痛苦。
首先建立一个XML文件作为解析对象:
<languages>
<language name = "java">
<author>Gosling</author>
</language>
<language name = "c++">
<author>Stroustrup</author>
</language>
</languages>
该对象放于源码上级目录中:
我们可以使用下面几种方法来解析XML:
1、使用DOMCategory
Document document=DOMBuilder.parse(newFileReader('../languages.xml'))
rootElement=document.documentElement
use(DOMCategory){
println 'Languages and Author'
languages=rootElement.language
languages.each{language->
println "${language.'@name'} authored by${language.author[0].text()}"
}
}
结果:
Languages and Author
java authored by Gosling
c++ authored by Stroustrup
2、使用XMLParser
languages=newXmlParser().parse('../languages.xml')
println'Languages and author'
languages.each{
println"${it.@name}authored by${it.author[0].text()}"
}
结果:
Languages and Author
java authored by Gosling
c++ authored by Stroustrup
3、使用XMLSlurper
languages=new XmlSlurper().parse("../languages.xml")
println 'Languages and author'
languages.language.each{
println "${it.@name}authored by${it.author[0].text()}"
}
结果:
Languages and author
java authored by Gosling
c++ authored by Stroustrup
二、创建XML
1、使用Gstring生成(类似于拼接)
langs= ['c++':'Stroustrup','java':'Gosling']
content=""
langs.each{
language,author->
fragment="""
${author}
"""
content+=fragment
}
xml="""
${content}
"""
println xml
结果:
2、使用MarkUpBuilder或者使用StreamingMarkupBuilder创建XML格式文件
langs= ['c++':'Stroustrup','java':'Gosling']
xmlDocument=new StreamingMarkupBuilder().bind{
mkp.xmlDeclaration()
mkp.declareNamespace(computer:'Computer')
languages{
comment<<"Created using StreamingMarkupBuilder"
langs.each{key, value ->
language(name: key) {
author(value)
}
}
}
}
println xmlDocument
结果: