简体   繁体   中英

Parsing in groovy between two tags?

I would like to parse this Gstring with groovy :

Format type : Key, Value.

   def txt = """ <Lane_Attributes>
                  ID,1
                  FovCount,600
                  FovCounted,598
                  ...
                  </Lane_Attributes> """

And get a map like :

Map = [ID:1, FovCount:600, FovCounted:598]

How can I :
- extract text between tag and ?,
- and convert to a map ?

Try this:

def map = [:]
txt.replaceAll('<.+>', '').trim().eachLine { line ->
   def parts = line.split(',')
   map[parts[0].trim()] = parts[1].trim().toInteger()
}
   def txt = """ <Lane_Attributes>
                  ID,1
                  FovCount,600
                  FovCounted,598

                  </Lane_Attributes> """

def map = new HashMap()
def lane = new XmlParser().parseText(txt)

 def content =  lane.text()


content.eachLine {
 line -> 

def dual =  line.split(',')
def key = dual[0].trim()
def val = dual[1].trim() 
//println "key: ${key} value: ${val}"
map.put(key,val)

}

println "map contains " +  map.inspect() 

//Will print: map contains ["FovCounted":"598", "ID":"1", "FovCount":"600"]

your problem is the fact that the contents between the tags will need to keep the same format throughout or this code will break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM