How can I retrieve an element from Groovy's GPathResult using a string that contains a perioid

后端 未结 2 1091
感动是毒
感动是毒 2020-12-04 03:31
def elementPath = \"elementA.elementB\"
xml.\"${elementPath}\".each {}

How to make this work? xml.elementA.elementB.each {} works.

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 03:59

    I can think of 2 ways round this...

    // Dummy Data for the testing
    def CAR_RECORDS = '''
        
          
            Australia
            Production Pickup Truck with speed of 271kph
          
          
            Isle of Man
            Smallest Street-Legal Car at 99cm wide and 59 kg in weight
          
          
            France
            Most Valuable Car at $15 million
          
        
      '''
    def xml = new XmlSlurper().parseText( CAR_RECORDS )
    def propNames = 'car.country'
    
    // METHOD 1
    // Split the propnames into individual properties, then use Inject to walk down this list
    // Passing the result to the next property
    propNames.split( /\./ ).inject( xml ) { obj, prop -> obj?."$prop" }.each { println it.text() }
    
    // METHOD 2
    // Construct a string to evaluate, and pass the xml object to it (it gets substituted in place of x)
    Eval.x( xml, "x.${propNames}" ).each { println it.text() }
    

    The javadoc page for Eval.x is here

    Hope this helps :-)

提交回复
热议问题