package dom4wspart3;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import java.util.*;
import java.io.File;
public class DOMCopySample {
public static void main(String argv[]) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document sourceDoc = db.parse(new File("inputXML.xml"));
NodeList invoices = sourceDoc.getElementsByTagName("invoice");
if (invoices==null)
return;
Document targetDoc = db.newDocument();
Element invoiceWrapper = targetDoc.createElementNS(
"http://domsamples.wrapper",
"invoiceWrapper");
targetDoc.appendChild(invoiceWrapper);
int numberOfInvoices = invoices.getLength();
for (int i=0;i<numberOfInvoices;i++) {
Element invoiceToBeImported = (Element)invoices.item(i);
invoiceWrapper.appendChild((Element)targetDoc.importNode(
invoiceToBeImported, true));
}//for
(new DOMCopySample()).printDocument(
"The target document looks like the following after importing all invoices:",
targetDoc);
}//try
catch (Exception e) {
e.printStackTrace(System.err);
}//catch
}//main
public void printDocument(String title, Document doc) {
System.out.println("");
System.out.println("");
System.out.println("*********************");
System.out.println(title+":");
try {
OutputFormat outputFormat = new OutputFormat(doc);
outputFormat.setPreserveSpace(true);
XMLSerializer serializer = new XMLSerializer(System.out, outputFormat);
serializer.serialize(doc);
System.out.println("");
}//try
catch (Exception e) {
e.printStackTrace(System.err);
}//catch
System.out.println("*********************");
System.out.println("");
System.out.println("");
}//printDocument
}//DOMCopySample