项目需要自动解析出hibernate.cfg.xml中数据库名用户名和密码。
直接使用以下方法解析,红色代码代表不是用hibernate.cfg.xml中指定的dtd,
不添加红色代码出现的问题是:自动查找hibernate.cfg.xml中指定的dtd,一般是从网上查找。当文件找不到时会报异常。
hibernate框架在不联网的情况下也可是正常使用,是因为框架本身使用自带的dtd不使用hibernate.cfg.xml中指定的dtd,只有Jar包中找不到dtd时,才会到网上查找。
public static Void getCon() {
// 得到sax解析器
SAXReader read = new SAXReader();
//防止到网络上查找DTD
read.setEntityResolver(new DTDEntityResolver());
// 通过文件得到输入流
InputStream is=null;
try {
// is = new FileInputStream(new File("D:/spaces/.metadata/.me_tcat/webapps/Doraemon/WEB-INF/classes/hibernate.cfg.xml"));
//is = new FileInputStream(new File("D:/struts.xml"));
is = new FileInputStream(new File("D:/hibernate.cfg.xml"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//在非静态的方法中可以直接用this.getclass.getResourceAsStream("/hibernate.cfg.xml");
try {
// 得到xml文档对象
Document doc = read.read(is);
//得到根元素
Element root=doc.getRootElement();
// xpath得到session-factory中的内容
Element e = (Element) root.selectSingleNode("session-factory");
// 得到root下面的集合,通过迭代器输出
Iterator it = e.elementIterator();
int i=0;
while (it.hasNext()) {
if(i==3)break;
Element ee = (Element) it.next();
// 得到属性name中的值
String key = ee.attributeValue("name");
// 得到文本框中的内容
String value = ee.getText();
//进行相应的匹配并且赋值
if (key.equals("hibernate.connection.username")) {
username = value;
i++;
continue;
} else if (key.equals("connection.url")) {
url = value;
i++;
continue;
} else if (key.equals("hibernate.connection.password")) {
password = value;
i++;
continue;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}