[jdom-interest] Get Element based on XPATH

Laurent Bihanic laurent.bihanic at atosorigin.com
Wed Jul 6 05:41:31 PDT 2005


Hi,

Kevin L. Cobb wrote:
> I have what I hope will be an easy answer to a simple question. Given a 
> Document and an XPATH expression, what is the best way to remove the 
> element at the given XPATH expression (assuming the expression points to 
> an element) and replace it with another value?

There's probably a clever way to do what you want do without using a loop but 
the following should work OK:

private void replace(Document doc, String selector, Element new) {
     Element old = XPath.selectSingleNode(document, selector);
     if (old != null) {
         Element parent = old.getParentElement();
         List l = parent.getChildren();
         for (int i=0; i<l.size(); i++) {
             Element e = (Element)(l.get(i));
             if (e == old) {
                 l.set(i, new);
                 break;
             }
         }
     }
}

Laurent


More information about the jdom-interest mailing list