[jdom-interest] How to replace an Element with Text?

Bradley S. Huffman hip at cs.okstate.edu
Sat Mar 27 20:25:13 PST 2004

Brad Cox writes:

> I've an XHTML processing application that supports persistent forms. 
> It needs to rewrite some elements (<input type="radio"> and <option> 
> elements, for example) as text elements (velocity macro calls that 
> add checked="checked" attributes).
> For example
> 	<input type="radio" ... > must be rewritten as #radioElement(...)
> 	<option>Value</option> 	must be rewritten as #optionElement(...)
> with suitable attributes and arguments of course.
> First try (iteration over the List returned by XPath) didn't work 
> because you can only delete elements, not replace them.

The list return from XPath isn't "live" so changes to it are not reflected
back in the tree.

> Second try was index through list and use set(index, new Text(...)) 
> to replace elements. That approach didn't work either. Debugger 
> showed that the list was modified propertly, but the changes didn't 
> affect the underlying DOM, just the list.
> Can someone explain why #2 didn't work and what I can do to fix it? Thanks!

Same reason. Try this, index throught the list and

    Element element = (Element) xpath_result.get(i); // Assumes xpath returned
                                                     // only Elements
    Parent parent = element.getParent();             // get the element's parent
    int index = parent.indexOf(element);             // and element's index
    parent.setContent(index, "#radioElement ...");   // replace it


Go Pokes!!!

More information about the jdom-interest mailing list