标签:
代码:
import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; 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 DOMdemo2 { public static void main(String[] args) { //(1)建立DocumentBuilderFactory,以取到DocumentBuilder DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=null; try { //(2)通过DocumentBuilderFactory取得DocumentBuilder builder=factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } //(3)定义Document的接口对象,通过DocumentBuilder进行DOM树的转换操作 Document doc=null; doc=builder.newDocument(); //(4)建立各个操作节点 Element addresslist=doc.createElement("addresslist"); Element linkman=doc.createElement("linkman"); Element name=doc.createElement("name"); Element email=doc.createElement("email"); //(5)设置节点的文本内容 name.appendChild(doc.createTextNode("张华")); linkman.appendChild(doc.createTextNode("sfasf@163.com")); //(6)设置节点关系 linkman.appendChild(name); linkman.appendChild(email); addresslist.appendChild(linkman); doc.appendChild(addresslist); //(7)输出文档到文件中 TransformerFactory tf=TransformerFactory.newInstance(); Transformer t=null; try { t=tf.newTransformer(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } t.setOutputProperty(OutputKeys.ENCODING,"UTF-8");//设置编码 DOMSource source=new DOMSource(doc);//输出文档 StreamResult result=new StreamResult(new File("D:"+File.separator+"Output.xml"));//指定输出位置 try { t.transform(source, result);//输出 } catch (TransformerException e) { e.printStackTrace(); } } }
运行结果:
标签:
原文地址:http://www.cnblogs.com/gugibv/p/5130986.html