日期:2014-05-18 浏览次数:20617 次
public void buildXml01(){
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
//创建一个新的document文档对象,这里返回的document是 org.w3c.dom.Document
Document document = db.newDocument();
//document.setXmlVersion("UTF-8");//默认UTF-8
Element root = document.createElement("ns1:MyRequest");
root.setAttribute("xmlns:ns1", "http://www.namespace1.com");
root.setAttribute("xmlns:ns2", "http://www.namespace2.com");
root.setAttribute("ns2:Token","1000");
Element element01 = document.createElement("ns2:Document");
element01.setAttribute("xmlns:ns2","http://www.namespace2.com");
element01.setAttribute("Archivo","2000");
element01.setAttribute("Type","XML");
Element element02 = document.createElement("ns2:Information");
element02.setAttribute("xmlns:ns2","http://www.namespace2.com");
element02.setAttribute("Sender","CN");
element02.setAttribute("Receiver","US");
Element element03 = document.createElement("ns1:Addenda");
element03.setAttribute("Attribute","S");
element03.setAttribute("value","10000");
document.appendChild(root);//这一步必不可少,绑定父子标签的关联关系
root.appendChild(element01);
root.appendChild(element02);
root.appendChild(element03);
//TransformerFactory这个工厂专门生产Transformer的实例,Transformer实例就可以把封装好的document变成xml格式的文档了
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
//文件写入器
PrintWriter printWriter = new PrintWriter(new FileOutputStream("c:\\server.xml"));
StreamResult result = new StreamResult(printWriter);
//执行写入操作
transformer.transform(source, result);
System.out.println("生成xml文件成功");
printWriter.close();
} catch (ParserConfigurationException e) {
e.print