2009年4月12日星期日

Parse XML file

Recently I have writen a XML file,which contains some information about database config,such as driveName,dbURL,userName,userPwd.Then by parsing it to get database-connected information.Therefore you can change the xml file directly to meet your special database neatly,needn't to chang your program.

I use mysql datadase.

database-config.xml

Use jdom API to parse database-config.xml to get driveName,dbURL,userName,userPwd.

configReader.java


package beaver;

import java.io.IOException;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class configReader {
private String driverName;
private String dbURL;
private String userName;
private String userPwd;

public Element getRoot(String fileName) {
Document doc=null;
//create parser object
SAXBuilder sax=new SAXBuilder();
try{
//parser XML doc,build a node tree,and return root
doc=sax.build(fileName);
}catch(JDOMException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
Element root=doc.getRootElement();
return root;
}
public void getDBInformation(Element root) throws Exception {
Element configInfo=root.getChild("config-info");
driverName=configInfo.getChild("driverName").getText();
dbURL=configInfo.getChild("dbURL").getText();
userName=configInfo.getChild("userName").getText();
userPwd=configInfo.getChild("userPwd").getText();
if(driverName==""){
throw new Exception("Database Driver Name is not set.");
}
if(dbURL==""){
throw new Exception("Database URL String is not set.");
}
if(userName==""){
throw new Exception("Database User Name is not set.");
}
if (userPwd==""){
throw new Exception("Database Password is not set.");
}
}
public static void main(String[] args) throws Exception {

configReader parser=new configReader();
parser.getDBInformation(parser.getRoot("E:/database-config.xml"));

}

public String getDriverName() {
return driverName;
}
public String getDbURL() {
return dbURL;
}
public String getUserName() {
return userName;
}
public String getUserPwd() {
return userPwd;
}
}

没有评论:

发表评论