1 /*
2 * To change this template, choose Tools | Templates3 * and open the template in the editor.4 */
5 packagexmlpackage;6
7 /**
8 *@authorXiaoTianCai9 */
10 /*
11 * 生成xml文件并输出到磁盘文件中,12 * xml文件不会格式整齐,但实际使用中格式没有任何关系13 */
14 importjava.io.File;15 importjava.io.IOException;16 importjavax.xml.parsers.DocumentBuilder;17 importjavax.xml.parsers.DocumentBuilderFactory;18 importjavax.xml.parsers.ParserConfigurationException;19 importjavax.xml.transform.OutputKeys;20 importjavax.xml.transform.Transformer;21 importjavax.xml.transform.TransformerConfigurationException;22 importjavax.xml.transform.TransformerException;23 importjavax.xml.transform.TransformerFactory;24 importjavax.xml.transform.dom.DOMSource;25 importjavax.xml.transform.stream.StreamResult;26 importorg.xml.sax.SAXException;27 importorg.w3c.dom.Document;28 importorg.w3c.dom.Element;29 importorg.w3c.dom.NodeList;30
31 public classDOMdemo_build_xml_test {32
33 public static voidmain(String[] args) {34 //(1)建立DocumentBuilderFactory,用于取得DocumentBuilder
35 DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();36 //(2)通过DocumentBuilderFactory,取得DocumentBuilder
37 DocumentBuilder builder = null;38 try{39 builder =factory.newDocumentBuilder();40 } catch(ParserConfigurationException e) {41 e.printStackTrace();42 }43 //(3)定义Document接口对象,通过DocumentBuilder类进行DOM树的转换操作
44 Document doc = null;45 doc = builder.newDocument(); //创建一个新文档46 //(4)建立各个操作节点
47 Element addresslist = doc.createElement("addresslist");//建立节点
48 Element linkman = doc.createElement("linkman");49 Element name = doc.createElement("name");50 Element email = doc.createElement("email");51 //(5)设置节点的文本内容,即为每一个节点添加文本节点
52 name.appendChild(doc.createTextNode("周敏丽"));//设置文本
53 email.appendChild(doc.createTextNode("1234567@163.com"));54 //(6)设置节点关系
55 linkman.appendChild(name); //子节点
56 linkman.appendChild(email);57 addresslist.appendChild(linkman);58 doc.appendChild(addresslist); //文本上的保存节点59 //(7)将文档输出到文件中
60 TransformerFactory tf =TransformerFactory.newInstance();61 Transformer t = null;62 try{63 t =tf.newTransformer();64 } catch(TransformerConfigurationException e1) {65 e1.printStackTrace();66 }67 t.setOutputProperty(OutputKeys.ENCODING, "GB2312"); //设置编码
68 DOMSource source = new DOMSource(doc); //输出文档
69 StreamResult result = new StreamResult(new File("web\\output.xml")); //指定输出位置
70 try{71 t.transform(source, result);72 } catch(TransformerException e) {73 e.printStackTrace();74 }75 }76 }