groovy解析xml

XML解析提供了XmlParser、XmlSlurper

XML生成提供了MarkupBuilder、StreamingMarkupBuilder类

 

XML操作: MarkupBuilder

MarkupBuilder (): Prints markup to System.out

 

 

import groovy.xml.*

def xml = new MarkupBuilder()
xml.langs("type":currecy){
     language("java")
     language("groovy")
     language("c++")
}

 

 

MarkupBuilder (PrintWriter pw): Sends markup to the given PrintWriter

import groovy.xml.*

def ps = new StringWriter()
def xml = new MarkupBuilder(ps)
xml.langs("type":currecy){
     language("java")
     language("groovy")
     language("c++")
}
println ps.toString()

 

XmlParser解析的是xml格式的字符串

import groovy.xml.*

def xml = """
<langs type="current">
  <language>Java</language>
  <language>Groovy</language>
  <language>JavaScript</language>
</langs>
"""

def langs = new XmlParser().parseText(xml)
println "type = ${langs.attribute("type")}"
langs.language.each{
  println it.text()
}

 

xml code

<langs type="current">
  <language>Java</language>
  <language>Groovy</language>
  <language>JavaScript</language>
</langs>

 

XmlParser进行xml解析

def langs = new XmlParser().parse("languages.xml")
println "type = ${langs.attribute("type")}"
langs.language.each{
  println it.text()
}

 

你可能感兴趣的:(groovy)