packagecom.clzhang.sample.xml;import java.io.*;import java.util.*;importorg.jdom2.Document;importorg.jdom2.Element;importorg.jdom2.input.SAXBuilder;importorg.jdom2.output.Format;importorg.jdom2.output.XMLOutputter;/*** 参考http://www.jdom.org/,需要下载最新包jdom-2.0.4.jar
* 下载包中没有API文档,需要参考http://www.jdom.org/docs/apidocs/index.html
* 目标:我们希望提供一个解决方案,在Java中使用XML就像Java本身那么简单。
* 它形如Java,它使用Java集合,它提供完全自然的API接口给Java开发人员, 它降低了使用XML的门槛。
* 相对DOM与SAX,它不是一个抽象层或增强这些API。相反,它提供了一个强大的,轻量的阅读和写作的复杂性和内存消耗的方案。*/
public classJDOMTest {//读取文件测试(其输入是writeXMLFile的输出)
public void parseByJDOM(String file) throwsException {
SAXBuilder sb= newSAXBuilder();
Document doc= sb.build(newFile(file));
Element root=doc.getRootElement();
List elements =root.getChildren();for(Element element : elements) {
String id= element.getAttribute("id").getValue();
System.out.println(element.getName()+ "\tid=" +id);
List children =element.getChildren();for(Element child : children) {
String name= child.getAttribute("name").getValue();
String value=child.getText();
System.out.println("\t" + child.getName() + "\t" + name + "=" +value);
}
}
}//写入文件测试
public void writeXMLFile(String filename) throwsException {//文档
Document doc = newDocument();//根节点
Element root = new Element("add");
doc.setRootElement(root);//子节点一
Element element = new Element("doc");
element.setAttribute("id", "1");
Element name= new Element("field");
name.setAttribute("name", "title");
name.setText("北京欢迎您");
Element content= new Element("field");
content.setAttribute("name", "content");
content.setText("北京真的欢迎您");
element.addContent(name);
element.addContent(content);
root.addContent(element);//子节点二
element = new Element("doc").setAttribute("id", "2");
name= new Element("field").setAttribute("name", "title");
name.setText("上海也欢迎您");
content= new Element("field").setAttribute("name", "content");
content.setText("上海真的也欢迎您");
element.addContent(name);
element.addContent(content);
root.addContent(element);//输出到文件,输出流及格式都设置为UTF-8
FileOutputStream fos = newFileOutputStream(filename);
OutputStreamWriter osw= new OutputStreamWriter(fos, "UTF-8");
Format format=Format.getPrettyFormat();
format.setEncoding("UTF-8");
XMLOutputter output= newXMLOutputter();
output.setFormat(format);
output.output(doc, osw);
osw.close();
fos.close();
}public static void main(String[] args) throwsException {
JDOMTest ins= newJDOMTest();
ins.writeXMLFile("bbs.xml");
ins.parseByJDOM("bbs.xml");
}
}