Groovy Xml 操作

MarkupBuilder 創(chuàng)建xml文檔

參考:https://www.ibm.com/developerworks/cn/java/j-pg05199/index.html

簡(jiǎn)單例子

def mb = new MarkupBuilder()
mb.book() {
       author('Lao Zhang')
       title('Groovy')
       publisher('中國(guó)郵電出版社')
       isbn("123456")
}

輸出為:

<book>
  <author>Lao Zhang</author>
  <title>Groovy</title>
  <publisher>中國(guó)郵電出版社</publisher>
  <isbn>123456</isbn>
</book>

輸出到文件到book.xml文件

def mb = new MarkupBuilder(new File('book.xml').newPrintWriter())
mb.book() {     // 偽方法 book() 創(chuàng)建book元素
  ...

簡(jiǎn)單例子2

獲取數(shù)據(jù),生成 xml

@Test
void test2() {
    def data = ['11111111': ['Groovy', 'Lao Zhang', '人民郵電出版社'],
                '22222222': ['Java In Mode', 'Zhang', '日?qǐng)?bào)出版社'],
                '33333333': ['Kotlin in Action', 'Jim', '對(duì)外出版社']]

    def mb = new MarkupBuilder(new File("book.xml").newPrintWriter())
    mb.library() {  // 偽方法創(chuàng)建library元素
        data.each { bk ->
            mb.book() {  // 創(chuàng)建book元素
                title(bk.value[0])
                author(bk.value[1])
                publisher(bk.value[2])
                isbn(number: bk.key)    // 新增number屬性
            }
        }
    }
}

文件內(nèi)容如下:

<library>
  <book>
    <title>Groovy</title>
    <author>Lao Zhang</author>
    <publisher>人民郵電出版社</publisher>
    <isbn number='11111111' />
  </book>
  <book>
...

XmlParser解析Xml

將xml文檔解析成樹的節(jié)點(diǎn),每個(gè)節(jié)點(diǎn)都有其名稱,value,屬性內(nèi)容與子節(jié)點(diǎn)信息;

@Test
void test3() {
    def parser = new XmlParser()
    def doc = parser.parse("book.xml")
    println("${doc.book[0].title[0].text()}")

    // doc.book 傳遞了一個(gè)節(jié)點(diǎn)列表,可使用each方法了
    // 迭代xml內(nèi)容
    doc.book.each() { bk ->
        println("${bk.title[0].text()}")
    }

    // 簡(jiǎn)化,輸出所有title
    doc.book.title.each() { title ->
         println(title.text())
    }
}

獲取節(jié)點(diǎn)屬性值 ['@number']

或者使用 Node.attribute("") 獲取單個(gè)屬性值,Node.attributes() 返回所有屬性值映射

@Testattriu
void test4() {
    // 通過(guò)['@number'] 獲取屬性 isbn值
    def parser = new XmlParser()
    def doc = parser.parse("book.xml")
    doc.book.isbn.each() { it ->
        println(it['@number'])
    }
}

解析xml,并分組示例

原xml如下,需要做成按 國(guó)籍 分組進(jìn)行輸出的 xml:

<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob</artist>
        <country>USA</country>
        <company>Columbia</company>
        <price>10.9</price>
        <year>1985</year>
    </cd>
    <cd>
        <title>Hide your heart</title>
        <artist>Jim</artist>
        <country>UK</country>
        <company>CBS Records</company>
        <price>8.9</price>
        <year>1988</year>
    </cd>
    <cd>
        <title>Still got the blues</title>
        <artist>Tom</artist>
        <country>UK</country>
        <company>Virgin Records</company>
        <price>10.2</price>
        <year>1990</year>
    </cd>
    <cd>
        <title>This is UK</title>
        <artist>Lee</artist>
        <country>UK</country>
        <company>Virgin Records</company>
        <price>12.20</price>
        <year>1990</year>
    </cd>
</catalog>

實(shí)現(xiàn)步驟:

  1. 解析原有xml,用map來(lái)存儲(chǔ)xml結(jié)構(gòu);
  2. 將map中的xml結(jié)構(gòu),采用 markupbuilder 重新生成xml文件;
    代碼如下:
doc.cd.each() { cd ->
        if (countryMap.containsKey(cd.country[0].text())) {
            def yearMap = countryMap.get(cd.country[0].text())
            def year = cd.year[0].text()
            if (yearMap.containsKey(year)) {
                yearMap[year] << cd.title[0].text()
            } else {
                yearMap[year] = [cd.title[0].text()]  // 此為list
            }
            countryMap[cd.country[0].text()] << yearMap
        } else {
            // 因?yàn)槭?map
            countryMap[cd.country[0].text()] = [(cd.year[0].text()): [cd.title[0].text()]]
        }
    }
    println(countryMap)
}

輸出如下:

[USA:[1985:[Empire Burlesque]], UK:[1988:[Hide your heart], 1990:[Still got the blues, This is UK]]]

  1. 生成分組的xml,代碼如下:
// 創(chuàng)建的新的xml
def mb = new MarkupBuilder(new File('group.xml').newPrintWriter())
mb.grouping() {     // 節(jié)點(diǎn) grouping
    countryMap.each { country, yearMap ->
        mb.country(name: country) { // 節(jié)點(diǎn) country
            yearMap.each { year, titleList ->
                mb.year(year: year) {  // year節(jié)點(diǎn)
                    titleList.each {
                        title(it)  // <title>xxx</title>
                    }
                }
            }
        }
    }
}

xml如下:

<grouping>
  <country name='USA'>
    <year year='1985'>
      <title>Empire Burlesque</title>
    </year>
  </country>
  <country name='UK'>
    <year year='1988'>
      <title>Hide your heart</title>
    </year>
    <year year='1990'>
      <title>Still got the blues</title>
      <title>This is UK</title>
    </year>
  </country>
</grouping>

使用XmlSlurper解析xml

使用 . 訪問(wèn)來(lái)操作xml節(jié)點(diǎn),如需要訪問(wèn)屬性 加 @
參考:
http://www.itdecent.cn/p/6e95030fa55d

xml 如下:

<book>
  <author>Lao Zhang</author>
  <title>Groovy</title>
  <publisher>中國(guó)郵電出版社</publisher>
  <isbn parent="parment">123456</isbn>
</book>
def root = new XmlSlurper()
      .parse(this.getClass().getClassLoader().getResource("files/book.xml").getPath())
println(root.isbn.@parent)      // 直接獲取屬性值,輸出:parment

忽略xml namespace的處理

在Android的layout xml中,默認(rèn)是有namespace的,比如我們解析一個(gè)布局文件獲取其 attribute,如下代碼:

xml 文件如下

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/id_edittext_container"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:background="@color/didi_page_bg"
        android:orientation="horizontal">
...
  1. 通過(guò) namespace的處理
// 使用Groovy xml 來(lái)解析
def root = new XmlParser().parse(this.getClass().getClassLoader()
          .getResource("files/address_search.xml").getPath())
// 指定namespace
def android = new Namespace("http://schemas.android.com/apk/res/android", "android")  
 root.each {
       println(it.attributes().get("android:layout_width"))  // 這里返回的是 null,獲取不到
       // 通過(guò)namespace對(duì)象,結(jié)合[] 來(lái)訪問(wèn)屬性值
       println(it.attributes()[android.layout_height])  // use namespace :android get layout_height
}
  1. 忽略namesapce
// 傳入2個(gè)false
def root = new XmlParser(false, false).parse(this.getClass().getClassLoader()
      .getResource("files/activity_address_search.xml").getPath())
root.each {
      println(it.attributes().get("android:layout_width"))  // no problem
}
  1. 例子:獲取xml中的ID的2種方式
def eachTxtFile(File file, closure) {
        if (file != null && file.exists()) {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))
            try {
                def line = null
                while ((line = br.readLine()) != null) {
                    closure.call(line)
                }
            } finally {
                br?.close()
            }
        }
    }

//////////////////////// 一行一行讀,并使用正則 ===== 
    /**
     * // android 中 為 xml 指定id的方式如下:
     def str1 = "@+id/button1"
     def str3 = "@id/button3"
     def str2 = "@android:id/button2"
     */
    @Test
    void test2() {
        // 獲取xml文件中的id value
        def file = new File(this.getClass().getClassLoader().getResource("files/activity_address_search.xml").getPath())
        def ids = []
        def pattern = ~/@((\+id)|(id)|(android:id))\/(.*)\"/
        eachTxtFile(file) { it ->
            def matcher = it =~ pattern
            if (matcher.find()) {
                println("${matcher[0][5]}")     // 獲取ID值
            }
        }
    }

//////////////////////// 使用xmlParser ===== 
  @Test
    void test4() {
// 使用Groovy xml 來(lái)解析
def root = new XmlParser(false, false).parse(this.getClass().getClassLoader()
        .getResource("files/activity_address_search.xml").getPath())
  // 閉包的遞歸, 先定義,再賦值
        def eachNode 
        eachNode = { node ->
            if (node.attributes().containsKey("android:id")) {
                println(node.attributes()["android:id"])  // no problem
            }
            node.value()?.each {
                eachNode.call(it)
            }
        }
        eachNode.call(root)
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,694評(píng)論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,285評(píng)論 6 342
  • 有人問(wèn):你為什么選擇北漂? 因?yàn)槟阍诒本┱f(shuō)夢(mèng)想,沒(méi)有人會(huì)嘲笑你 有一個(gè)女孩,2013年9月開始就讀于南京的一所農(nóng)林...
    者者skye閱讀 406評(píng)論 0 2
  • 憶當(dāng)年,卷發(fā)突眼嬉笑顏,豪飲一大碗,徹夜暢談,談笑若淡然,哭者笑者鬧者間,瘋狂一年復(fù)一年!徹夜談,大被眠!!多了真...
    請(qǐng)叫我小參酒閱讀 473評(píng)論 0 0
  • 從明天起我要改掉我的臭脾氣,希望你能信任我,原諒我。
    于耀東閱讀 240評(píng)論 0 0

友情鏈接更多精彩內(nèi)容