Search code examples
javaxmlxpathdom4j

Using Xpaths on cloned dom4j Object produces differnt results


The following code:

    Document document = DocumentHelper.createDocument();
    Element e1 = document.addElement("Element1")
            .addElement("Element2")
            .addAttribute("id", "1");
    System.out.println((Element)e1.selectSingleNode("//*[@id=\"1\"]"));
    Element e2 = e1.createCopy();
    System.out.println((Element)e2.selectSingleNode("//*[@id=\"1\"]"));

produces this output:

org.dom4j.tree.DefaultElement@6f75e721 [Element: <Element2 attributes: [org.dom4j.tree.DefaultAttribute@3fb4f649 [Attribute: name id value "1"]]/>]
null

If i use:

    System.out.println(e1.asXML().equals(e2.asXML()));

it returns true. Why does this happen? Am i using the wrong way to clone the elment? I am genuinly confused here...


Solution

  • Because the copy is not attached to a Document, see createCopy() method comment

    /**
     * <p>
     * Creates a deep copy of this element The new element is detached from its
     * parent, and getParent() on the clone will return null.
     * </p>
     * 
     * @return a new deep copy Element
     */
    Element createCopy();
    
    
    Element e2 = e1.createCopy();
    System.out.println(e2.getDocument()); // NULL
    

    Dom4j needs the Document element to resolve namespaces and their prefixes among other things. If you add your e2 to a document then it will return a result.

    DocumentHelper.createDocument().add(e2);
    System.out.println((Element)e2.selectSingleNode("//*[@id=\"1\"]"));