我想解析一個XML文件來設置我的數據庫的連接。但是我只返回了空字符串。有人可以檢查我做錯了什麼嗎?Java:空值解析XML文件
Java類(DBCONFIG僅僅是一個的細節字符串類別)
public class XMLReader {
public Dbconfig read(){
Dbconfig conf = new Dbconfig();
try {
File file = new File("database.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
//System.out.println("Root element " + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("database");
Element element = (Element) nodeLst.item(0);
NodeList url = element.getElementsByTagName("url");
conf.url = url.item(0).toString();
NodeList driver = element.getElementsByTagName("driver");
conf.driver = driver.item(0).toString();
NodeList username = element.getElementsByTagName("username");
conf.username = username.item(0).toString();
NodeList password = element.getElementsByTagName("password");
conf.password = password.item(0).toString();
System.out.format("####Printing XML configuration:%s %s %s %s \n",conf.url, conf.driver, conf.username, conf.password);
} catch (Exception e) {
e.printStackTrace();
}
return conf;
}
}
XML文件(它應該只提供1個數據庫中的配置):
<?xml version="1.0" encoding="UTF-8"?>
<database>
<url>jdbc:mysql://localhost:3306/db</url>
<driver>com.mysql.jdbc.Driver</driver>
<username>admin</username>
<password>admin</password>
</database>
輸出是:
####Printing XML configuration:[url: null] [driver: null] [username: null] [password: null]
我只是想提供我的客戶的可能性,以在不提供源代碼的情況下更改我的桌面應用程序的數據庫詳細信息,我不會重新發明任何東西,只是良好的做法,而不是聲稱學分。感謝您的幫助 – RNO 2013-02-11 18:14:15
@RNO:即使在這種情況下,您也可以使用['java.util.Properties'](http://docs.oracle.com/javase/6/docs/api/java/util/ Properties.html),它有內置的方法來讀寫'.properties'文件和'xml'文件。請參見['Properties#loadFromXML()'](http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html#loadFromXML(java.io.InputStream))和['Properties #storeToXML()'](http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html#storeToXML(java.io.OutputStream中,%20java.lang.String))。不需要自己解析'xml'。 – Asaph 2013-02-11 19:55:31