tags:

views:

441

answers:

2
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;


public class Main {
    public static void main(String[] args){
     Company cp17 = new Company();
     Person ps1 = new  Person("Barry","15900000000");
     Person ps2 = new Person("Andy","15800000000");
     cp17.employee.add(ps1);
     cp17.employee.add(ps2);

     Document document = DocumentHelper.createDocument();
     Element companyElement = document.addElement("company");
     for(Iterator<Person> personIter = cp17.employee.iterator();personIter.hasNext();){
      Person nextEmployee = personIter.next();
      Element employee = companyElement.addElement("employee");
      employee.addAttribute("name",nextEmployee.name);
      employee.addAttribute("phoneNumber",nextEmployee.phoneNumber);
     }

     Document document2 = DocumentHelper.createDocument();
        Element compnies = document.addElement("companies");
        //move cp17 to document2 as a child of companies.
        //ERROR companies.add(cp17);
     XMLWriter xmlWriter = new XMLWriter();
     try{
     xmlWriter.write(document2);
     xmlWriter.close();
     }
     catch(Exception e){
      e.printStackTrace();
     }
    }
}

I creat two Document Object , now I want to move one Element and it's child Elements to another.How can i do that .Can anyone tell me, thank you.^_^

+2  A: 

Use the standard DOM method Document.importNode to bring content from one document into another. http://www.dom4j.org/dom4j-1.6.1/apidocs/org/dom4j/dom/DOMDocument.html#importNode%28org.w3c.dom.Node,%20boolean%29

Element companyElement2= document2.importNode(companyElement, true);
companies.appendChild(companyElement2);

(Assuming that this line:

Element compnies = document.addElement("companies");

is supposed to read:)

Element companies = document2.addElement("companies");
bobince
Does this apply to DOM4J?
jamesh
Yes, dom4j supports standard DOM methods as well as its own wide-ranging extensions/alternatives to the standard.
bobince
For anyone reading importNode is not implemented in dom4j 1.6.1 (or earlier I guess).
Konstantin
A: 

Element.createCopy() is probably what you should use:

Konstantin