groovy 之 對xml的解析 和 對文件的讀取

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文件進行解析,代碼如下:
/**
* @author yangy
* Aug 21, 2012
*/

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的一些使用。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章