以下代码:
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\"]"));
产生以下输出:
org.dom4j.tree.DefaultElement@6f75e721 [Element: <Element2 attributes: [org.dom4j.tree.DefaultAttribute@3fb4f649 [Attribute: name id value "1"]]/>]
null
如果我使用:
System.out.println(e1.asXML().equals(e2.asXML()));
它返回 true。为什么会出现这种情况?我是否使用了错误的方式来克隆元素?我真的很困惑......
最佳答案
由于副本未附加到 Document
,请参阅 createCopy()
方法注释
/**
* <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 需要 Document 元素来解析 namespace 及其前缀等。如果您将 e2
添加到文档中,它将返回结果。
DocumentHelper.createDocument().add(e2);
System.out.println((Element)e2.selectSingleNode("//*[@id=\"1\"]"));
关于java - 在克隆的 dom4j 对象上使用 Xpath 会产生不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30358278/