[jdom-interest] Get Element based on XPATH

Kevin L. Cobb kevin.cobb at emergint.com
Wed Jul 6 06:05:33 PDT 2005


Thanks for the response. I realize that I misstated my question. I want
to replace an Elements text() value and not the entire element. I came
up with this method . . . 


   public static Document replaceElementValue(Document inDoc, String
targetElementXPath, String newValue)
                  throws XmlException {

      Document newDoc = null;
      try {
         newDoc = (Document) inDoc.clone();
         Object elementToReplace =
XPath.selectSingleNode(newDoc.getRootElement(), targetElementXPath);
         if (elementToReplace instanceof Element) {
            ((Element) elementToReplace).setText(newValue);
         } else {
            throw new XmlException("Target content is not an Element
object. " +
                    "XPath must resolve to an Element or the value of
the Elemnet cannot be replaced.");
         }
      } catch (JDOMException je) {
         throw new XmlException(je.getMessage(), je);
      }

      return newDoc;
   } 


-----Original Message-----
From: Laurent Bihanic [mailto:laurent.bihanic at atosorigin.com] 
Sent: Wednesday, July 06, 2005 8:42 AM
To: Kevin L. Cobb
Cc: jdom-interest at jdom.org
Subject: Re: [jdom-interest] Get Element based on XPATH


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