Groovy read values from xml

2019-08-05 14:50发布

问题:

I have a Sample Code where I'm trying to read data from an xml file and manipulating the values. This worked perfectly fine when I tried it on http://ideone.com

In my actual code I'm calling something like this

def xmlFile = "path/to/xmlfile.xml"
def tcproj = new XmlParser().parseText( getTemplate(xmlFile).toString() )

But when I use the same if condition specified in the Sample Code in my actual code, I get a completely different result.

On trying to debug I found that the result varied a lot. The result on my actual code with this when I tried to do

println records.supported_versions.version.any { println it; it.toString().matches( /$ver/ ) }

was this

version[attributes={}; value=[6.0.35.A]]
version[attributes={}; value=[7.0.25.B]]
false

When I do

println records.supported_versions.version.toString()

I get a result

[version[attributes={}; value=[6.0.35.A]], version[attributes={}; value=[7.0.25.B]]]

Can someone help me understand what's happening here and how to solve this?

回答1:

You're using XmlParser instead of XmlSlurper as in that example...

To use XmlParser, you need to change the code to:

class xmlWorker {
  static def tcproj = '''<tcs>
                           <supported_versions>
                             <version>6.0.35.A</version>
                             <version>7.0.25.B</version>
                           </supported_versions>
                         </tcs>'''
}
def records = new XmlParser().parseText(xmlWorker.tcproj)

def ver = "6.0.35.A"

println "Version: " + ver

println records.supported_versions.version.any {
  println it.text()
  it.text().matches( /${ver}/ )
}

if( records.supported_versions.version.any { it.text().matches( /${ver}/ ) } ) {
  println "if"
} else {
  println "else"
}