匯入jdom.jar,jdom提供了比較簡單易用的讀寫xml檔案的方法
一、寫XML
樣本:
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
public class XmlWriter {
private Element wRoot = null;
private Document wDoc = null;
public void initwRoot() {
try {
wRoot = new Element("database");
wDoc = new Document(wRoot);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void writeXml(String strFileName) {
try {
File f = new File(strFileName);
if(f.exists()){
f.delete();
}
f.createNewFile();
XMLOutputter XMLOut = new XMLOutputter();
XMLOut.output(wDoc, new FileOutputStream(strFileName));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
在XML中添加節點:
public Element addNode(Element eCur, String nodename){
Element eChild = null;
try{
eChild = new Element(nodename);
eCur.addContent(eChild);
}
catch(Exception e){
e.printStackTrace();
}
return eChild;
}
通過上述方法得到文檔對象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 class XmlReader {
private Element rRoot = null;
public void initrRoot(String strXMLPathFile) throws IOException, JDOMException {
SAXBuilder builder = new SAXBuilder();
Document read_doc = builder.build(strXMLPathFile);
rRoot = read_doc.getRootElement();
}
}
通過上述代碼得到xml檔案的根節點rRoot,接下來可以調用rRoot的List<Element> getChildren(String nodeName) 方法得到其子節點,同理,可以依次遍曆各個子節點的getChilren()方法;通過Element的String getAttributeValue(String attrName)可得到節點的屬性值