Groovy中的xml操作

解析xml数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
final String xml = '''
<response version-api="2.0">
<value>
<books id="1" classification="android">
<book available="20" id="1">
<title>疯狂Android讲义</title>
<author id="1">李刚</author>
</book>
<book available="14" id="2">
<title>第一行代码</title>
<author id="2">郭林</author>
</book>
<book available="13" id="3">
<title>Android开发艺术探索</title>
<author id="3">任玉刚</author>
</book>
<book available="5" id="4">
<title>Android源码设计模式</title>
<author id="4">何红辉</author>
</book>
</books>
<books id="2" classification="web">
<book available="10" id="1">
<title>Vue从入门到精通</title>
<author id="4">李刚</author>
</book>
</books>
</value>
</response>
'''
def xmlSluper = new XmlSlurper()
def resp = xmlSluper.parseText(xml)
println resp.value.books[1].book[0].title.text()

Vue从入门到精通

xml数据简单查找

1
2
3
4
5
6
7
8
9
10
11
//xml,resp同上
def list = []
resp.value.books.each {books->
books.book.each { book ->
def author = book.author.text()
if (author == '李刚'){
list.add(book)
}
}
}
println list.toListString()

[疯狂Android讲义李刚, Vue从入门到精通李刚]

深度遍历

1
2
3
4
5
6
7
8
9
//深度遍历
def titles1 = resp.depthFirst().findAll {book ->
return book.author.text() == '李刚'
}
def titles2 = resp.depthFirst().findAll {node ->
node.name() == 'book' && node.@id == '2'
}
println titles1
println titles2

[疯狂Android讲义李刚, Vue从入门到精通李刚]

[第一行代码郭林]

广度遍历

1
2
3
4
5
//广度遍历
def name = resp.value.books.children().findAll { node->
node.name() == 'book' && node.@id=='2'
}
println name

第一行代码郭林

生成xml

Groovy中生成xml用的是MarkupBuilder

例如要生成如下的xml文档

1
2
3
4
5
<langs type='current' count='3' mainstream='true'>
<language flavor='static' version='1.5'>Java</language>
<language flavor='dynamic' version='1.6.0'>Groovy</language>
<language flavor='dynamic' version='1.9'>JavaScript</language>
</langs>
1
2
3
4
5
6
7
8
def sw = new StringWriter()
def xmlBuilder = new MarkupBuilder(sw)
xmlBuilder.langs(type: 'current', count: '3', mainstream: 'true') {
language(flavor: 'static', version: '1.5', "Java")
language(flavor: 'dynamic', version: '1.6', "Groovy")
language(flavor: 'dynamic', version: '1.9', "JavaScript")
}
println sw

Java
Groovy
JavaScript

一般我们生成xml都是用实体对象动态生成的

定义class如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//对应xml中的Langs结点
class Langs {
String type = "current"
int count = 3
boolean mainstream = true
def language = [new Language(flavor: "static", version: 1.5, value: "java"),
new Language(flavor: "dynamic", version: 1.6, value: "Groovy"),
new Language(flavor: "dynamic", version: 1.9, value: "JavaScript")]
}
//对应xml中的language结点
class Language {
String flavor
String version
String value
}
1
2
3
4
5
6
7
8
9
def langs = new Langs()
xmlBuilder.langs(type: langs.type, count: langs.count, mainstream: langs.mainstream) {
langs.language.each { lang ->
language(flavor: lang.flavor,
version: lang.value,
lang.value)
}
}
println sw

上面的生成方式也是可以的