JDOM是一種解析XML的Java工具包,官方地址:http://www.jdom.org/,目前版本為1.1。
盡管JDOM 在性能測試時表現不佳,在測試 10M 文檔時內存溢出 ,但是他API比較簡單,容易上手。
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class DOMCreator ...{
public static void main(String[] args) throws IOException, JDOMException ...{
Document table = new Document(new Element(Constants.DATA_TABLE));
Element row = new Element(Constants.DATA_ROW);
Element item = new Element(Constants.DATA_ITEM);
item.setText("data");
row.setContent(item);
table.getRootElement().setContent(row);
Format format = Format.getPrettyFormat();
XMLOutputter outputter = new XMLOutputter(format);
FileWriter writer = new FileWriter("sample.xml");
outputter.output(table, writer);
writer.close();
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new File("sample.xml"));
XMLOutputter domstream = new XMLOutputter();
domstream.output(document, System.out);
}
}
常量聲明文件:
public interface Constants ...{
public static String DATA_TABLE = "Table";
public static String DATA_ROW = "Row";
public static String DATA_ITEM = "Item";
}