w3c.dom组件写xml文件实例

w3c.dom组件写xml文件实例

package com.yanek.demo.xml.test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
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 W3cDomWriteXml {

 /**
  * @param args
  */
 public static void main(String[] args) {

  
  Document doc = null;
  try {
   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   DocumentBuilder db = dbf.newDocumentBuilder();
   doc = db.newDocument(); 
   
   Element root = doc.createElement("actions");
   doc.appendChild(root);
   
   Element action1 = doc.createElement("action");
   Element action2 = doc.createElement("action");
   
   root.appendChild(action1);
   root.appendChild(action2);
   action1.setAttribute("path","/test");

   action2.setAttribute("path","/user");
   action2.setAttribute("class","com.yanek.mystruts.demo.UserAction");
   action1.setAttribute("class","com.yanek.mystruts.demo.TestAction");
   
   
   Element forward1 = doc.createElement("forward");
   Element forward2 = doc.createElement("forward");
   
   Element forward3 = doc.createElement("forward");
   Element forward4 = doc.createElement("forward");
   
   
   action1.appendChild(forward1);
   action1.appendChild(forward2);
   
   action2.appendChild(forward3);
   action2.appendChild(forward4);
   
   forward1.setAttribute("name","test");

   forward2.setAttribute("name","failure");
   forward1.setAttribute("url","test.jsp");
   forward2.setAttribute("url","failure.jsp"); 
   
   
   forward3.setAttribute("name","user");

   forward4.setAttribute("name","failure");
   forward3.setAttribute("url","list.jsp");
   forward4.setAttribute("url","failure.jsp");
   
   
   
   
   File file = new File("d://type111.xml");
   
   if(!file.exists()) {
    file.createNewFile();
   }
 
   BufferedWriter bw = new BufferedWriter(new FileWriter(file));
   
   //将内存里的dom 转为xml文件
   TransformerFactory tff =TransformerFactory.newInstance();
   Transformer tf = tff.newTransformer();
   tf.setOutputProperty("encoding", "utf-8");
   tf.transform(new DOMSource(doc), new StreamResult(bw));
   bw.close();
   
  } catch(Exception ex) {
   ex.printStackTrace();
  }
  
  
  

 }

}

 

 

生成xml文件:

 

<?xml version="1.0" encoding="utf-8"?><actions><action class="com.yanek.mystruts.demo.TestAction" path="/test"><forward name="test" url="test.jsp"/><forward name="failure" url="failure.jsp"/></action><action class="com.yanek.mystruts.demo.UserAction" path="/user"><forward name="user" url="list.jsp"/><forward name="failure" url="failure.jsp"/></action></actions>

上一篇:WebSocket-用nodejs搭建服务器


下一篇:NanoXML组件解析xml实例