xml文件为:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" >
<persistence-unit name="jdztjxPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>db.TUser</class>
<class>db.TDept</class>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="root"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/jdztjx?useUnicode=true&characterEncoding=UTF-8"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
</properties>
</persistence-unit>
</persistence>
最终解析代码为:
try {
String fp = "persistence.xml";//此处为相对路径
Map map = new HashMap();
map.put("persistence", "http://java.sun.com/xml/ns/persistence");//将persistence注册为namesapce的名称
SAXReader saxReader = new SAXReader();
File file = new File(fp);
System.out.println(file.getAbsolutePath());
saxReader.getDocumentFactory().setXPathNamespaceURIs(map);
Document document = saxReader.read(file);
String xpathUser="//persistence:persistence/persistence:persistence-unit[@name='"+PersistenceCollectUnitName+"']/persistence:properties/persistence:property[@name='hibernate.connection.username']";//书写xpath时使用 persistence
List <Element> persisList = document.selectNodes(xpathUser);
//System.out.println(persisList.size());
Element elUser=persisList.get(0);
user=elUser.attributeValue("value");
//...省略一点
}catch(DocumentException ex){
Logger.getLogger(DbConn.class.getName()).log(Level.SEVERE, null, ex);
}