在克隆的 dom4j 对象中使用 Xpath 会产生不同的结果
Using Xpaths on cloned dom4j Object produces differnt results
以下代码:
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()));
它 returns 是的。为什么会这样?我是否使用了错误的方式来克隆元素?我真的很困惑...
因为副本未附加到 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 元素来解析名称空间及其前缀等。如果您将 e2
添加到文档,那么它将 return 结果。
DocumentHelper.createDocument().add(e2);
System.out.println((Element)e2.selectSingleNode("//*[@id=\"1\"]"));
以下代码:
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()));
它 returns 是的。为什么会这样?我是否使用了错误的方式来克隆元素?我真的很困惑...
因为副本未附加到 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 元素来解析名称空间及其前缀等。如果您将 e2
添加到文档,那么它将 return 结果。
DocumentHelper.createDocument().add(e2);
System.out.println((Element)e2.selectSingleNode("//*[@id=\"1\"]"));