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>