import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class XMLCreator {
public static void  main(String args[]){
  try{
  	// 为解析XML文件创建DOM对象
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new File("mylist.xml"));
    // 文档初始化
    doc.normalize();
    Element root = doc.getDocumentElement();
    // 创建新的节点
    Node node_list = doc.createElement("list");
    Node node_id = (Node) doc.createElement("id");
    Node tmp1 = doc.createTextNode("tmp1");
    tmp1.setNodeValue("3");
    node_id.appendChild(tmp1);
    Node node_name = doc.createElement("username");
    Node tmp2 = doc.createTextNode("tmp2");
    tmp2.setNodeValue("Cat");
    node_name.appendChild(tmp2);
    Node node_time = doc.createElement("time");
    Node tmp3 = doc.createTextNode("tmp3");
    tmp3.setNodeValue("05-6-28 10:27:36");
    node_time.appendChild(tmp3);
    Node node_homepage = doc.createElement("homepage");
    Node tmp4 = doc.createTextNode("tmp4");
    tmp4.setNodeValue("http://www.cat.com");
    node_homepage.appendChild(tmp4);
    Node node_email = doc.createElement("email");
    Node tmp5 = doc.createTextNode("tmp5");
    tmp5.setNodeValue("cat@cat.com");
    node_email.appendChild(tmp5);
    Node node_context = doc.createElement("context");
    Node tmp6 = doc.createTextNode("tmp6");
    tmp6.setNodeValue("Cat's test.");
    node_context.appendChild(tmp6);
    node_list.appendChild( node_id ); 
    node_list.appendChild( node_name );
    node_list.appendChild( node_time );
    node_list.appendChild( node_homepage );
    node_list.appendChild( node_email );
    node_list.appendChild( node_context );
    root.appendChild(node_list);
	TransformerFactory tFactory =TransformerFactory.newInstance();
	Transformer transformer = tFactory.newTransformer();
	DOMSource source = new DOMSource(doc);
	StreamResult result = new StreamResult(new java.io.File("mylist2.xml"));
	transformer.transform(source, result);    

  }catch(Exception e){
    e.printStackTrace();
  }
}
}
