我正在尝试解析一个 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]