在外部存储GPath表达式

时间:2017-11-01 15:42:17

标签: xml groovy gpath

我使用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) )    
}

1 个答案:

答案 0 :(得分:2)

非常接近这个问题: 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)