简体   繁体   English

Groovy 从 xml 读取值

[英]Groovy read values from xml

I have a Sample Code where I'm trying to read data from an xml file and manipulating the values.我有一个示例代码,我在其中尝试从 xml 文件读取数据并处理这些值。 This worked perfectly fine when I tried it on http://ideone.com当我在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.但是当我在实际代码中使用示例代码中指定的相同if条件时,我得到了完全不同的结果。

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?有人可以帮助我了解这里发生的事情以及如何解决这个问题吗?

You're using XmlParser instead of XmlSlurper as in that example...您正在使用XmlParser而不是该示例中的XmlSlurper ...

To use XmlParser, you need to change the code to:要使用 XmlParser,您需要将代码更改为:

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"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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