Java自動XML作成
[size=large]
package test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
public class CreateXml {
/**
* @param args
* @throws ParserConfigurationException
*/
public static void main(String[] args) throws ParserConfigurationException {
//
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
// root
Element root = doc.createElement("Student");
// name
Element item = doc.createElement("name");
//
item.appendChild(doc.createTextNode("wangyanping"));
//
root.appendChild(item);
// age
item = doc.createElement("age");
item.appendChild(doc.createTextNode("28"));
// age
root.appendChild(item);
// high
item = doc.createElement("high");
item.appendChild(doc.createTextNode("180cm"));
root.appendChild(item);
item = doc.createElement("score");
// score lessons
Element lessons = doc.createElement("lessons");
// lessons lesson
Element lesson = doc.createElement("java");
//
lesson.appendChild(doc.createTextNode("90"));
//
lessons.appendChild(lesson);
//
item.appendChild(lessons);
lessons = doc.createElement("lessons");
lesson = doc.createElement("struts");
lesson.appendChild(doc.createTextNode("80"));
lessons.appendChild(lesson);
item.appendChild(lessons);
lessons = doc.createElement("lessons");
lesson = doc.createElement("hibernet");
lesson.appendChild(doc.createTextNode("100"));
lessons.appendChild(lesson);
item.appendChild(lessons);
root.appendChild(item);
//
doc.appendChild(root);
//
OutputFormat format = new OutputFormat(doc, "utf-8", true);
StringWriter stringOut = new StringWriter();
XMLSerializer serial = new XMLSerializer(stringOut,format);
// DOM
try {
serial.asDOMSerializer();
serial.serialize(doc.getDocumentElement());
//
PrintStream ps = new PrintStream(new FileOutputStream("new.xml"));
// xml
ps.println(stringOut.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
[/size]