Reputation: 2643
I'm using groovy to process some XML and I've read through the following tutorial http://groovy-lang.org/processing-xml.html. I understand how to replaceNodes but what I'd like to do is store these gpath expressions in a file and read them in at run time to "detect" things like urls, database connection properties and replace node values/attributes as required.
Does anyone know if this is possible?
[edit] Example as requested
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) )
}
Upvotes: 0
Views: 153
Reputation: 28634
very close to this question: 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)
Upvotes: 2