在Groovy XML Parser中使用String作为代码 [英] Using a String as code with Groovy XML Parser

查看:190
本文介绍了在Groovy XML Parser中使用String作为代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对groovy很陌生 - 我希望这是一件简单的事情来解决。

  def root = new XmlParser()返回一个XML文档, .parseText(xmlString)
println root.foo.bar.text()

想要做的是,从文件或数据库中加载路径的foo.bar部分,以便我可以这样做:

 def paths = [foo.bar,tashiStation.powerConverter] //为这个例子定义
paths.each {
path - >
println path +\ t+ root.path.text()
}

显然,编写的代码不起作用......我想也许这会起作用:

  paths.each { 
path - >
println path +\t+ root。$ {path}.text()
}

...但它没有。我基于Groovy的第153页的DSL初步解决方案,可以以类似的方式创建动态方法。



想法?理想的解决方案不会添加大量代码,并且不会添加任何其他库依赖项。我总是可以回头用JDOM来做这些东西,但我希望有一个优雅的Groovy解决方案。

解决方案

这非常类似于这个问题来自3天前这个问题



您基本上需要在上拆分路径,然后沿着这个列表走下去在你的对象图中移动

  def val = path.split(/\./).inject(root){obj,节点 - > obj?$ node}?text()
println$ path\t $ val

在这种情况下应该这样做: - )


I am new to groovy - I am hoping this is a simple thing to solve. I am reading in an xml document, and then I am able to access data like this:

def root = new XmlParser().parseText(xmlString)
println root.foo.bar.text()

What I would like to do, is to have loaded the "foo.bar" portion of the path from a file or data base, so that I can do something like this:

def paths = ["foo.bar","tashiStation.powerConverter"] // defined for this example
paths.each { 
    path ->
    println path + "\t" + root.path.text()
}

Obviously the code as written does not work... I thought maybe this would work:

paths.each { 
    path ->
    println path + "\t" + root."${path}".text()
}

...but it doesn't. I based my initial solution on pg 153 of Groovy for DSL where dynamic methods can be created in a similar way.

Thoughts? The ideal solution will not add significant amounts of code and will not add any additional library dependencies. I can always fall back to doing this stuff in Java with JDOM but I was hoping for an elegant groovy solution.

解决方案

This is very similar to this question from 3 days ago and this question

You basically need to split your path on . and then walk down this list moving through your object graph

def val = path.split( /\./ ).inject( root ) { obj, node -> obj?."$node" }?.text()
println "$path\t$val"

Should do it in this instance :-)

这篇关于在Groovy XML Parser中使用String作为代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆