Java HTML / XML How to - Split child node from XML file into their own XML files


We would like to know how to split child node from XML file into their own XML files.


//from   www.  j a  v  a  2s.c  o m
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
  static public void main(String[] arg) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("foo.xml");

    TransformerFactory tranFactory = TransformerFactory.newInstance();
    Transformer aTransformer = tranFactory.newTransformer();

    NodeList list = doc.getFirstChild().getChildNodes();

    for (int i = 0; i < list.getLength(); i++) {
      Node element = list.item(i).cloneNode(true);

      if (element.hasChildNodes()) {
        Source src = new DOMSource(element);
        FileOutputStream fs = new FileOutputStream("k" + i + ".xml");
        Result dest = new StreamResult(fs);
        aTransformer.transform(src, dest);