最近做了一个关于读取项目中prodect.xml文件中数据库连接的信息,这是测试源码,可直接粘用。
public class B {
public static void main(String[] args) {
Connection conn ;
ResultSet rs = null ;
Statement st = null ;
String ip = "";
String port = "";
String dbname = "";
String user = "";
String pwd = "";
//项目路径
String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"product.xml";
filePath = filePath.replaceAll("file:/", "");
filePath = filePath.replaceAll("%20", " ");
filePath = filePath.trim();
// 创建saxReader对象
SAXReader reader = new SAXReader();
Document document;
try {
document = reader.read(new File(filePath));
//获取根节点元素对象
Element node = document.getRootElement();
// 获取根节点下,子节点名称为datasource的元素。
Element element = node.element("datasource");
// 获取datasource下所有ds的节点
List<Element> list = element.elements("ds");
for (Element e : list){
//获取ds节点下的子节点
Element link = e.element("link");
ip = link.attributeValue("ip");
port = link.attributeValue("port");
dbname = link.attributeValue("dbname");
user = link.attributeValue("user");
pwd = link.attributeValue("pwd");
System.out.println("ip="+ip+"/port="+port+"/dbname="+dbname+"/user="+user+"/pwd="+pwd);
}
}catch(Exception e){
e.printStackTrace();
}
}
}