import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
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.Element;
public class XMLGen {
private final int count;
private final int depth;
private Document dom;
public XMLGen() {
this( 4, 4);
}
public XMLGen( final int count, final int depth) {
this.count = count;
this.depth = depth;
}
public Document getDOM() throws ParserConfigurationException {
if ( dom == null) dom = createDOM();
return dom;
}
private Document createDOM() throws ParserConfigurationException {
Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
d.appendChild( d.createElement( "root"));
appendChildNodes( d.getDocumentElement(), 0);
return d;
}
private void appendChildNodes( Element e, int lvl) {
for ( int i=0; i<count; i++) {
Element c = e.getOwnerDocument().createElement( "tag" + i + "_" + lvl);
e.appendChild( c);
if ( lvl <= depth) appendChildNodes( c, lvl+1);
}
}
public static void output( Document doc, OutputStream out) throws TransformerException {
Transformer trans = TransformerFactory.newInstance().newTransformer();
trans.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "no");
trans.setOutputProperty( OutputKeys.INDENT, "yes");
trans.setOutputProperty( OutputKeys.STANDALONE, "yes");
trans.setOutputProperty( OutputKeys.ENCODING, "ISO-8859-1");
trans.setOutputProperty( OutputKeys.METHOD, "xml");
DOMSource src = new DOMSource( doc);
trans.transform( src, new StreamResult( out));
}
public static void main( String[] args) throws Exception {
XMLGen xg = new XMLGen();
output( xg.getDOM(), new FileOutputStream( "file.xml"));
}
}