Element root=document.getRootElement(); //删除类型为society的book节点 Element book_society=(Element)document.selectSingleNode("//book[@type='society']"); root.remove(book_society); System.out.println("1。正确的删除了类型为society的book节点"); System.out.println(document.asXML());
//删除sex节点 Element sex=(Element)root.selectSingleNode("//sex");
remove public boolean remove(Element element)Removes the given Element if the node is an immediate child of this branch. If the given node is not an immediate child of this branch then the Node.detach()method should be used instead.
Parameters: element - is the element to be removed Returns: true if the element was removed 从中我们可以看出,remove只能用在它自己的直接孩子节点上,不能用在孙子节点上,因为sex节点不是root节点的直接孩子节点,所以不能删除;而sex节点却是author节点的直接孩子节点,所以第三个输出可以删除。
//取出doc_author的author节点,添加到doc_book的根结点 Element author=(Element)doc_author.selectSingleNode("//author"); doc_book.getRootElement().add(author); System.out.println(doc_book.asXML()); } 调用CombineDocument函数,会出现以下错误:
org.dom4j.IllegalAddException: The node "org.dom4j.tree.DefaultElement@17bd6a1 [Element: <author attributes: []/>]" could not be added to the element "root" because: The Node already has an existing parent of "root" at org.dom4j.tree.AbstractElement.addNode(AbstractElement.java:1521) at org.dom4j.tree.AbstractElement.add(AbstractElement.java:1002) at xml_chb.dom4j_chb.CombineDocument(dom4j_chb.java:189) at xml_chb.dom4j_chb.main(dom4j_chb.java:199) Exception in thread "main"
appendContent public void appendContent(Branch branch)Appends the content of the given branch to this branch instance. This method behaves like the Collection.addAll(java.util.Collection) method.
Parameters: branch - is the branch whose content will be added to me.