Parsing in groovy between two tags?

I would like to analyze this Gstring using groovy:

Type of format: Key, Value.

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

And get a card like:

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

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

+3
source share
3 answers

Try the following:

def map = [:]
txt.replaceAll('<.+>', '').trim().eachLine { line ->
   def parts = line.split(',')
   map[parts[0].trim()] = parts[1].trim().toInteger()
}
+3
source
   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 be printed: the card contains ["FovCounted": "598", "ID": "1", "FovCounted": "600"]

Your problem is that the content between the tags will have to support the same format in everything or this code will break

+2
source

Source: https://habr.com/ru/post/1744409/


All Articles