使用groovy访问XML元素

时间:2015-04-28 16:33:39

标签: groovy xml-parsing

我需要根据传递的命令行参数解析xml文件。只有两个参数传递给groovy程序。我可以在传递两个参数时解析并获得结果,但是在未传递可选参数(第二个参数)时无法使程序正常工作。

<env> 
    <environment name="qa">
        <server name="qaserver1">
            <vip>12.13.14.15</vip>
            <vip>12.13.14.16</vip>
        </server>
        <server name="qaserver2">
            <vip>12.13.14.17</vip>
            <vip>12.13.14.18</vip>
        </server>
    </environment>
</env>

当在参数

中未传递serverName时,需要此代码块才能工作
// Assuming both parameters are passed, this block works
def envName = "qa"
def serverName = "qaserver1"
def env = new XmlSlurper().parse("vips.xml")
env.environment.find{ environment -> 
    environment.@name == envName
}.server.find { server -> 
    server.@name == serverName
}.vip.each{ 
    println it.text() 
}

1 个答案:

答案 0 :(得分:0)

这是一种方法。您可以使用Groovy的内置CliBuilder来解析命令行参数。

我在脚本中定义了XML,但您可以继续读取文件。

这里的要点是def vips部分:必须有一个条件来检查是否提供了serverName。如果不是,则必须从XML获取所有服务器。注意.vip.flatten()无论environment.server...中的结果如何都会执行def cli = new CliBuilder() cli.envName required: true, "Environment name", args: 1 cli.serverName required: false, "Server name", args: 1 def opt = cli.parse args if (!opt) return def xml = '''<env> <environment name="qa"> <server name="qaserver1"> <vip>12.13.14.15</vip> <vip>12.13.14.16</vip> </server> <server name="qaserver2"> <vip>12.13.14.17</vip> <vip>12.13.14.18</vip> </server> </environment> </env>''' def envName = opt.envName def serverName = opt.serverName def env = new XmlSlurper().parseText xml environment = env.environment.find { it.@name.text() == envName } def vips = ((serverName) ? { environment.server.find { it.@name == serverName } } : { environment.server } )().vip.flatten() vips.each { println it.text() }

library(sqldf)
x = sqldf("
  SELECT *
  FROM Data1 d1 JOIN Data2 d2
  ON d1.Hour = d2.Hour2
  AND ABS(d1.Minute - d2.Minute2) <= 1
")