Java中配置文件的三种配置位置以及读取方式:
同包:Demo1.class.getResourceAstream("db.properties");
根路径:Demo1.class.getResourceAstream("/db.properties");
WIN-INF安全路径:context.getResourceAstream("/WEB-INF/db.properties");
节点读取的方式:
selectNodes:读取节点
selectSingleNode:读取头节点
attributeValue:获取属性值
getText:获取节点文本
Xpath的使用:
/:定位路径 @:属性
具体使用方法请参考下图:
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<!-- 1.数据库相关 -->
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.url">jdbc:mysql://localhost:3306/t207?useUnicode=true&characterEncoding=UTF-8</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 2.调试相关 -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- 开启二级缓存 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 开启查询缓存 -->
<property name="hibernate.cache.use_query_cache">true</property>
<!-- EhCache驱动 -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- 3.实体类映射文件 -->
<!-- <mapping resource="entity/user.hbm.xml"/> -->
<mapping resource="entity/worker.hbm.xml" />
<mapping resource="entity/student.hbm.xml" />
<mapping resource="entity/user.hbm.xml" />
<mapping resource="entity/order.hbm.xml" />
<mapping resource="entity/orderItem.hbm.xml" />
<mapping resource="entity/treeNode.hbm.xml" />
<mapping resource="entity/book.hbm.xml" />
<mapping resource="entity/category.hbm.xml" />
</session-factory>
</hibernate-configuration>
package test;
import java.io.InputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class Zy2 {
public static void main(String[] args) throws Exception {
InputStream is = Zy2.class.getResourceAsStream("hibernate.cfg.xml");
//创建xml文件读取工具类对象SaxReader
SAXReader sr =new SAXReader();
//读取.xml配置文件
Document doc = sr.read(is);
List<Node> nodes = doc.selectNodes("//*");
System.out.println(nodes.size());
for (Node node : nodes) {
Element el =(Element)node;
System.out.println(node.getText());
if(el.attributeValue("name")!=null) {
System.out.println(el.attributeValue("name"));
}
if(el.attributeValue("resource")!=null) {
System.out.println(el.attributeValue("resource"));
}
}
}
}