【问题标题】:Store GPath expressions externally在外部存储 GPath 表达式
【发布时间】:2025-12-20 14:15:07
【问题描述】:

我正在使用 groovy 处理一些 XML,并且我已经阅读了以下教程 http://groovy-lang.org/processing-xml.html。我了解如何替换节点,但我想做的是将这些 gpath 表达式存储在一个文件中,并在运行时读取它们以“检测”诸如 url、数据库连接属性之类的内容,并根据需要替换节点值/属性。

有谁知道这是否可行?

[编辑] 按要求举例

def books = '''
    <response version-api="2.0">
        <value>
            <books>
                <book available="20" id="1">
                    <title>Don Xijote</title>
                    <author id="1">Manuel De Cervantes</author>
                </book>
                <book available="14" id="2">
                    <title>Catcher in the Rye</title>
                   <author id="2">JD Salinger</author>
               </book>
               <book available="13" id="3">
                   <title>Alice in Wonderland</title>
                   <author id="3">Lewis Carroll</author>
               </book>
               <book available="5" id="4">
                   <title>Don Xijote</title>
                   <author id="4">Manuel De Cervantes</author>
               </book>
           </books>
       </value>
    </response>
'''


def response = new XmlParser().parseText(books)

response.value.books.book[0].author.replaceNode{
        author(id:"99s","Harper Lee")
}


// None of the following will work, but hopefully it shows what I'd like to do
// I'd like to store the path expression as a string 
def path = "response.value.books.book[0].author"

// 
path.replaceNode{
    author(getReplacementValueFromSomeLookup(path) )    
}

【问题讨论】:

  • 您介意显示您的示例输入和所需的输出 xml 吗?

标签: xml groovy gpath


【解决方案1】:

非常接近这个问题: How to get key from ArrayList nested in JSON using Groovy and change its value

def books = '''
    <response version-api="2.0">
        <value>
            <books>
                <book available="20" id="1">
                    <title>Don Xijote</title>
                    <author id="1">Manuel De Cervantes</author>
                </book>
                <book available="14" id="2">
                    <title>Catcher in the Rye</title>
                   <author id="2">JD Salinger</author>
               </book>
               <book available="13" id="3">
                   <title>Alice in Wonderland</title>
                   <author id="3">Lewis Carroll</author>
               </book>
               <book available="5" id="4">
                   <title>Don Xijote</title>
                   <author id="4">Manuel De Cervantes</author>
               </book>
           </books>
       </value>
    </response>
'''


def response = new XmlParser().parseText(books)

def path = "ROOT.value.books.book[0].author"

Eval.me('ROOT',response, path).replaceNode{
    author('DEMO')    
}

println groovy.xml.XmlUtil.serialize(response)

【讨论】:

  • 感谢您,这似乎是我所看到的最佳答案。我最初建议的方法最终感觉不是正确的方法,但感谢您的回答。我真正想要的是用于 XML/JSON 的 SQL,GPath/XPath 只是感觉有点密集。
最近更新 更多