加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

groovy 之 对xml的解析 和 对文件的读取

发布时间:2020-12-14 16:54:22 所属栏目:大数据 来源:网络整理
导读:Groovy 是 Java 平台上设计的面向对象编程语言。这门动态语言拥有类似 Python、Ruby 和 Smalltalk 中的一些特性,可以作为 Java 平台的脚本语言使用。Groovy 的语法与 Java 非常相似,以至于多数的 Java 代码也是正确的 Groovy 代码。Groovy 代码动态的被编
Groovy 是 Java 平台上设计的面向对象编程语言。这门动态语言拥有类似 Python、Ruby 和 Smalltalk 中的一些特性,可以作为 Java 平台的脚本语言使用。Groovy 的语法与 Java 非常相似,以至于多数的 Java 代码也是正确的 Groovy 代码。Groovy 代码动态的被编译器转换成 Java 字节码。由于其运行在 JVM 上的特性,Groovy 可以使用其他 Java 语言编写的库。


对文件的解析

1.创建customers.xml文件,文件内容如下:
<? xml version ="1.0" encoding ="UTF-8" ?>
< customers >
?? < corporate >
???? < customer name ="bill gates" company ="microsoft" > </ customer >
???? < customer name ="steve jobs" company ="apple" > </ customer >
???? < customer name ="bill dyh" company ="sun" > </ customer >
?? </ corporate >
?? < consumer >
???? < customer name ="jone Doe" > </ customer >
???? < customer name ="jane Doe" > </ customer >????
?? </ consumer >
</ customers >
2.创建.groovy的类 FileOpration.groovy,代码如下 (注意:代码和xml文件放在同一个包下)
/**
* @author yangy
* Aug 21,2012
*/

public class FileOpration{

????
?? static void main(String[]args){
???? /* 对file文件进行读取操作*/
????def path =????FileOpration. class.getResource("").path;
????def number = 0
???? //对xml文件进行解析
???? new File(path+'customers.xml').eachLine{
??????line ->
??????number++
??????println "$number:$line"
????}
????
???? /*递归 输出所有的文件名称*/
???? new File('.').eachFileRecurse{
??????println it
????}
??}
????
}

哦,对了,忘记了groovy的每行代码可以不写分号的,当然加上也可以

下面的是对xml的解析,我感觉相当犀利,groovy内部可能对其做了很强大的优化,这是后话了,上代码
1. xml文件还是上面的文件
2.创建XmlOpration.groovy类,对xml文件进行解析,代码如下:
public class XmlOpration{

????
?? static void main(String[]args){
???? /*对xml进行读取操作*/
???? def path = XmlOpration. class.getResource("").path;
???? def customers = new XmlSlurper().parse( new File(path + "customers.xml"))
???? /*对文件进行解析*/
???? for(customer in customers.corporate.customer){
????????println "${customer.@name} works for${customer.@company}";
???? }
??}
????
}

对xml的解析和对文件的读取就到此为止了,当然可以写一些封装的方法,来供自己的项目调用也是很不错的,可以弄成一个强大的类库,之后会写对string/list的一些使用。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读