JDom讀寫XML(程式碼)

mouqj發表於2007-09-01
SAXBuilder builder;
Document doc;
Element root;

public ConfigOperater() {
builder = new SAXBuilder();
try {
doc = builder.build(DataUtil.CONFIG_PATH);
root = doc.getRootElement();
}
catch (IOException ex) {
ex.printStackTrace();
}
catch (JDOMException ex) {
ex.printStackTrace();
}
}

//JDom讀取XML

public void readConfig() {
List allConfigDB = root.getChildren("TargetDB");
for(int i=0; i Element dbEle = (Element)allConfigDB.get(i);
Database database = new Database(dbEle.getAttributeValue("dbType"),
dbEle.getAttributeValue("id"),dbEle.getAttributeValue("dbIp"),
Integer.parseInt(dbEle.getAttributeValue("dbPort")),dbEle.getAttributeValue("dbName"),
dbEle.getAttributeValue("dbUser"),dbEle.getAttributeValue("dbPwd"),
dbEle.getAttributeValue("dbServer"),dbEle.getAttributeValue("clientLocale"),
dbEle.getAttributeValue("dbLocale"));
DataUtil.ALL_DB.addElement(database);
}
//DataBase db
}

//JDom寫入XML

public void writeToConfig() {
Element dbEle = new Element("TargetDB");
dbEle.setAttribute("id", DataUtil.curDB.getDbConName());
dbEle.setAttribute("dbType", DataUtil.curDB.getDBType());
dbEle.setAttribute("dbServer", DataUtil.curDB.getDbServer());
dbEle.setAttribute("dbName", DataUtil.curDB.getDbName());
dbEle.setAttribute("dbUser", DataUtil.curDB.getDbUser());
dbEle.setAttribute("dbPwd", DataUtil.curDB.getDbPwd());
dbEle.setAttribute("dbIp", DataUtil.curDB.getDbIp());
dbEle.setAttribute("dbPort", Integer.toString(DataUtil.curDB.getDbPort()));
dbEle.setAttribute("dbLocale", DataUtil.curDB.getDbLocale());
dbEle.setAttribute("clientLocale", DataUtil.curDB.getClientLocale());

root.addContent(dbEle);
try {
XMLOutputter outPutter = new XMLOutputter();
PrintWriter outWriter = new PrintWriter(new BufferedWriter(new FileWriter(DataUtil.CONFIG_PATH)));
outPutter.output(doc, outWriter);
}
catch (java.io.IOException e) {
e.printStackTrace();
}
}

[@more@]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/11049438/viewspace-967520/,如需轉載,請註明出處,否則將追究法律責任。

相關文章