XML文件生成
1 import java.io.* ; 2 import org.w3c.dom.* ; 3 import javax.xml.parsers.* ; 4 import javax.xml.transform.* ; 5 import javax.xml.transform.dom.* ; 6 import javax.xml.transform.stream.* ; 7 8 public class DOMDemo { 9 public static void main(String args[]) throws Exception { 10 // 取得DocumentBuilderFactory类的对象 11 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ; 12 // 取得DocumentBuilder类的对象 13 DocumentBuilder build = factory.newDocumentBuilder() ; 14 Document doc = build.newDocument() ; // 创建一个新的XML文档 15 Element addresslist = doc.createElement("addresslist") ; 16 Element linkman = doc.createElement("linkman") ; 17 Element name = doc.createElement("name") ; 18 Element email = doc.createElement("email") ; 19 // 设置节点内容 20 name.appendChild(doc.createTextNode("李兴华")) ; 21 email.appendChild(doc.createTextNode("mldnqa@163.com")) ; 22 // 该设置各个节点的关系 23 linkman.appendChild(name) ; // name是linkeman的子节点 24 linkman.appendChild(email) ; // email是linkman的子节点 25 addresslist.appendChild(linkman) ; 26 doc.appendChild(addresslist) ; 27 TransformerFactory tf = TransformerFactory.newInstance() ; 28 Transformer t = tf.newTransformer() ; 29 t.setOutputProperty(OutputKeys.ENCODING, "GBK") ; // 处理中文的 30 DOMSource source = new DOMSource(doc) ; // 准备输出文档 31 StreamResult result = new StreamResult(new File("d:"+File.separator+"output.xml")) ; 32 t.transform(source,result) ; 33 } 34 }
运行结果是:
1 <?xml version="1.0" encoding="GBK" standalone="no"?><addresslist><linkman><name>李兴华</name><email>mldnqa@163.com</email></linkman></addresslist>