使用Java解析XML文件(一) JDOM篇
时间:2011-01-29 csdn博客 沈斌
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";
}
|