生成“id”XML标记时Groovy的MarkupBuilder异常

时间:2013-01-11 18:35:21

标签: java xml grails groovy markupbuilder

我正在尝试构建XML提要,而Groovy的MarkupBuilder让我感到头疼:

 def newsstandFeed(def id) {
    def publication = Publication.get(id)
    def issues = issueService.getActiveIssuesForPublication(publication)
    def updateDate = DateUtil.getRFC3339DateString(publication.lastIssueUpdate)

    def writer = new StringWriter()
    writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
    def xml = new MarkupBuilder(writer)
    xml.feed('xmlns':"http://www.w3.org/2005/Atom", 'xmlns:news':"http://itunes.apple.com/2011/Newsstand") {
        updated("${updateDate}")
        issues.each { issue ->
            entry {
                id (issue.id)
                updated("${DateUtil.getRFC3339DateString(issue.lastUpdated)}")
                published("${DateUtil.getRFC3339DateString(issue.releaseDate)}")
                summary(issue.summary)
                "news:cover_art_icons" {
                    "news:cover_art_icon" (size:"SOURCE", src:"${issue.cover.remotePath}")
                }
            }
        }
    }

    return writer.toString()
}

我得到了这个例外:

Class groovy.lang.MissingMethodException 
No signature of method: java.lang.String.call() is applicable for argument types: (org.codehaus.groovy.runtime.GStringImpl) values: [CYB_001] Possible solutions: wait(), any(), wait(long), any(groovy.lang.Closure), take(int), each(groovy.lang.Closure)

“CYB_001”是第一个“id”属性。

如果我将“id”重命名为“ids”或其他任何东西,它会起作用,并返回一个正确的XML文档:

            ....
            issues.each { issue ->
            entry {
                ids ("${issue.id}")
                ...

为什么会发生这种情况的任何想法,以及我如何解决这个问题?

环境是Grails 2.1.1(所以Groovy 1.8,我假设)

2 个答案:

答案 0 :(得分:3)

在我看来,您的XML构建器正在尝试在环境中引用一些 String 变量。由于groovy构建器拦截了丢失的方法调用,如果他们找到引用,他们将尝试应用它。以下代码可以重现您的错误:

def id = ""

new groovy.xml.MarkupBuilder().xml {
  id "90"
}

以下情况很好:

def ids = ""

new groovy.xml.MarkupBuilder().xml {
  id "90"
}

重命名id变量应该可以解决问题


<强>更新

使用与作用域中的变量同名的标记的另一种方法是使用(丑陋的)GString:

def id = ""

new groovy.xml.MarkupBuilder().xml {
  "${'id'}" "90"
}

答案 1 :(得分:0)

遇到同样的情况并通过构建器对其进行限定,为我解决了问题。

def writer = new StringWriter()
    def builder = new MarkupBuilder(writer)
    builder.executions() {
        project.scalaVersions.each { scalaVersion ->
            def scalaMajorVer = '_' + scalaVersion.split('\\.')[0..1].join('.')
            def artifactIdStr = publication.artifactId.replaceAll(/_[0-9.]+$/, '') + scalaMajorVer

            execution() {
                builder.id(artifactIdStr) // qualify with builder to avoid collision
                phase('deploy')
                goals() { goal('deploy-file') }
                configuration() {
                    groupId(publication.groupId)
                    artifactId(artifactIdStr)
                    builder.version(project.version) // ditto.
                }
            }
        }
    }