第六堂课2(配置文件及dom4j+xpath解析xml文件)
一、Java 中配置文件的三种配置位置及读取方式
1.XML和*.properties(属性文件)/ini
2.存放位置
1.src根目录下
Xxx.class.getResourceAsStream("/config.properties");
理解:
1.Xxx:类名
2.getResourceAsStream:通过流得到资源
3./config.properties:绝对路径(/表示上级目录)
例如:
2.与读取配置文件的类在同一包
Xxx.class.getResourceAsStream(“config2.properties”);
例如:
3.WEB-INF(或其子目录下)
ServletContext application=this.getServletContext();
InputStream is=application.getResourceAsStream("/WEB-INF/config3.properties");
注释:(需要下载插件propetid)下载后放置eclipse里面
本知识点注1:
1.*.properties文件
2.key=value
3.#注释
4.Properties.load(is)
二、XML的作用
1.配置
1..properties
2..xml
3.*.ini
2.数据交换
1.xml(使用webservice技术,难度比较大)
2.json(比较方便,键值对存储方式)
三、dom4j+xpath解析xml文件
1.DOM由节点组成(Node)
1.元素节点(也就是标签)
2.属性节点(属性名)
3.文本节点(属性值)
2.xpath是等同(相当于)数据库的select语句
1.document.selectNodes(xpath):查一组数据
2.document.selectSingleNode(xpath):查单个数据
3.dom4j它是java语言专门提供的一个程序,用来解析XML文件的
本知识点注:
xpath中的特殊符合代表
1./:定位
2.@:属性
3.[]:条件
例如1(案例一及结果):找到所有节点
代码(解析):
// InputStream is=Demo2.class.getResourceAsStream("/config.xml"); //demo4j 读取 SAXReader reader=new SAXReader(); //开始读取 Document document=reader.read(is); //获取文档中的根目录 Element rootElement=document.getRootElement(); //获取到文本中的所有action List<Element> actionElementList=rootElement.selectNodes("/config/action"); //获取action下面的所有节点 遍历 for(Element actionElement:actionElementList) { //获取action下的属性节点和文本节点 String path=actionElement.attributeValue("path"); String type=actionElement.attributeValue("type"); System.out.println("path:"+path+",type:"+type); //获取action下的元素节点 List<Element> forwardElementList= actionElement.selectNodes("forward"); //遍历获取forward的属性节点及文本节点 for(Element forwardElement:forwardElementList) { String name=forwardElement.attributeValue("name"); String forwardPath=forwardElement.attributeValue("path"); String redirect=forwardElement.attributeValue("redirect"); System.out.println("name:"+name+",forwardPath:"+forwardPath+",redirect:"+redirect); } }
结果:
例如2(案例二及结果):练习:找path=/loginAction 的action 下的name=success forward 的path值
代码(解析): */
*/InputStream is=Demo2.class.getResourceAsStream("/config.xml"); //demo4j 读取 SAXReader reader=new SAXReader(); //开始读取 Document document=reader.read(is); //获取文档中的根目录 Element rootElement=document.getRootElement(); String path2="/config/action[@path='/loginAction']/forward[@name='success']/@path" ; Node node=rootElement.selectSingleNode(path2); System.out.println(node); System.out.println(node.getStringValue());
结果: