Search code examples
javaxmlgroovy

Groovy set text of node that has children


I have a node in an xml document that has the following general structure:

String xml = "
<root>
    <firstNode class="first">SomeText<childNode class="child">SomeMoreText</childNode></firstNode>
</root>"

I want to modify the text of the firstNode node. So I want to change the value of "SomeText" to something else, like "NewText". So the above xml would look like this:

<root>
    <firstNode class="first">NewText<childNode class="child">SomeMoreText</childNode></firstNode>
</root>"

I can get the firstNode node using the XmlParser class:

def firstNode = new groovy.xml.XmlParser().parseText(xml).root[0]

From the Node doc I am able to get the "SomeText" value using firstNode.localText()[0] but I can't figure out how to set that text. Somehow I was thinking of doing firstNode.setValue() but I don't know what to pass in that function.

Thanks for any ideas!


Solution

  • You need to manipulate the node's children directly firstNode.children().set(0, "foo"). Furthermore, the root node is implicit, so you need to omit it.

    String xml = """
    <root>
        <firstNode class="first">SomeText<childNode class="child">SomeMoreText</childNode></firstNode>
    </root>
    """
    def root = new groovy.xml.XmlParser().parseText(xml)
    def firstNode =  root.children()[0]
    firstNode.children().set(0, "foo")
    def nodeAsText = groovy.xml.XmlUtil.serialize(root)
    println nodeAsText
    

    Try it in the Groovy Web Console