shuttle
shuttle

Reputation: 153

XmlSlurper: Changing text in element with namespace

I don't understand why xml."con:cred"."ser:user" = "modified_username" doesn't change the text. Can someone explain this?

input = """
<kuk:acc xmlns:kuk="kuk">
    <con:cred xmlns:con="http://www.bea.com/wli/sb/resources/config">
        <ser:user xmlns:ser="http://www.bea.com/wli/sb/services">username</ser:user>
    </con:cred>
</kuk:acc>
"""

def xml = new XmlSlurper(keepWhitespace:true).parseText(input).declareNamespace(
    ser:"http://www.bea.com/wli/sb/services",
    con:"http://www.bea.com/wli/sb/resources/config")
println xml."con:cred"."ser:user" 

xml."con:cred"."ser:user" = "modified_username" // That doesn't work
println xml."con:cred"."ser:user" 

xml.cred.user = "modified_username" // That works
println xml."con:cred"."ser:user" 

/*
def outputBuilder = new StreamingMarkupBuilder() 
String result = outputBuilder.bind{ mkp.yield xml }
println result
*/

Upvotes: 2

Views: 1453

Answers (1)

jalopaba
jalopaba

Reputation: 8119

I've been digging in this problem some time and was about to ask just the same thing. Given that the method invoked when using the overloaded '=' operator is putAt(int, Object), a closer look into GPathResult code:

public void putAt(final int index, final Object newValue) {
    final GPathResult result = (GPathResult)getAt(index);

    if (newValue instanceof Closure) {
        result.replaceNode((Closure)newValue);
    } else {
        result.replaceBody(newValue);
    }
}

shows that replaceBody should be invoked. As *tim_yates* points out, replaceBody works well, so it seems that replaceNode is invoked instead (I cannot see why). Digging in NodeChildren's replaceNode, we can see that

protected void replaceNode(final Closure newValue) {
    final Iterator iter = iterator();
    while (iter.hasNext()) {
        final NodeChild result = (NodeChild) iter.next();
        result.replaceNode(newValue);
    }
}

the closure never gets called, so nothing is done when replaceNode is invoked. So I think that there's a bug in replaceNode (it does nothing), and when doing xml."con:cred"."ser:user" = "modified_username" the right part of the expression is evaluated as a Closure (I need help in this point to understand why :-).

Upvotes: 1

Related Questions