Java tutorial
import java.io.FileOutputStream; 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 javax.xml.transform.stream.StreamResult; 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); fs.close(); } } } }