groovy XmlSlurper使用一

  • 读取xml

这里我们不想直接把正则写到代码里,而是想通过xml配置的方式,可以通过修改配置进行更多博客的扩展。Groovy的XmlSlurper是一个非常强大的xml分析工具,可以用与XPath对应的GPath来完成xml的读写。

config.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<? xml version = "1.0" encoding = "UTF-8" ?>
<!--this is a config file.You can edit this file to support more blogs.-->
< config >
     < blog >
         < name >sina</ name >
         < list > <![CDATA[http://blog\.sina\.com\.cn/s/articlelist_[\d_]+\.html]]> </ list >
         < post > <![CDATA[http://blog\.sina\.com\.cn/s/blog_\w+\.html]]> </ post >
     </ blog >
     < blog >
         < name >diandian</ name >
         < list > <![CDATA[http://[\w+\-]+\.diandian\.com/page/\d+]]> </ list >
         < post > <![CDATA[http://[\w+\-]+\.diandian\.com/post/[^"'#]+]]> </ post >
     </ blog >
</ config >

我们使用Groovy将xml读入到map中,并使用config.blog.name作为map的key。

1
2
3
4
5
6
7
def lists = [:]
def posts = [:]
def config = new XmlSlurper().parse( new File( "config.xml" ))
         config.blog. each {
             lists[it.name.toString()]=it.list.toString()
             posts[it.name.toString()]=it.post.toString()
}

  值得注意的是it.name返回的是一个Node类型的对象,需要将其转换为字符串作为key,不然lists['xxx']是永远取不到值的!

摘自原文:http://progressdaily.diandian.com/post/2012-06-12/40028671462

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值