代码之家  ›  专栏  ›  技术社区  ›  Fabien Barbier

在groovy中解析两个标记?

  •  3
  • Fabien Barbier  · 技术社区  · 15 年前

    我想用groovy解析这个gstring:

    格式类型:键,值。

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

    得到一张地图,比如:

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

    我怎样才能:
    -在标记和之间提取文本?,
    -转换成地图?

    3 回复  |  直到 15 年前
        1
  •  3
  •   Burt Beckwith    15 年前

    试试这个:

    def map = [:]
    txt.replaceAll('<.+>', '').trim().eachLine { line ->
       def parts = line.split(',')
       map[parts[0].trim()] = parts[1].trim().toInteger()
    }
    
        2
  •  2
  •   Vinny    15 年前
       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() 
    

    //将打印:地图包含[“fovcounted”:“598”,“id”:“1”,“fovcount”:“600”]

    您的问题是,标记之间的内容需要始终保持相同的格式,否则此代码将中断