导入jdom.jar,jdom提供了比较简单易用的读写xml文件的方法
一、写XML
示例:
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
public classXmlWriter {
privateElementwRoot=null;
privateDocumentwDoc=null;
public voidinitwRoot() {
try{
wRoot=newElement("database");
wDoc=newDocument(wRoot);
}
catch(Exception e) {
e.printStackTrace();
}
}
public voidwriteXml(String strFileName) {
try{
File f = newFile(strFileName);
if(f.exists()){
f.delete();
}
f.createNewFile();
XMLOutputter XMLOut = newXMLOutputter();
XMLOut.output(wDoc,newFileOutputStream(strFileName));
}
catch(Exception e) {
e.printStackTrace();
}
}
}
在XML中添加节点:
public Element addNode(Element eCur, String nodename){
Element eChild = null;
try{
eChild = newElement(nodename);
eCur.addContent(eChild);
}
catch(Exception e){
e.printStackTrace();
}
returneChild;
}
通过上述方法得到文档对象wDoc,以及其根节点wRoot, 调用方法addNode()可以往根节点中插入子节点,返回的子节点对象eChild,同理,可以往子节点eChild中插入下一级的子节点。最后调用writeXml()方法保存为xml文件
二、读XML
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
public classXmlReader {
private ElementrRoot=null;
public voidinitrRoot(String strXMLPathFile)throwsIOException, JDOMException {
SAXBuilder builder = newSAXBuilder();
Document read_doc = builder.build(strXMLPathFile);
rRoot= read_doc.getRootElement();
}
}
通过上述代码得到xml文件的根节点rRoot,接下来可以调用rRoot的List getChildren(String nodeName) 方法得到其子节点,同理,可以依次遍历各个子节点的getChilren()方法;通过Element的String getAttributeValue(String attrName)可得到节点的属性值