目录
一.Java中配置文件的三种配置位置及读取方式
1.同包
类名.class.getResourceAsStream("文件名字")
2.根路径
类名.class.getResourceAsStream("/文件名字")
3.WIN-INF安全路径
context.getResourceAsStream("/WIN-INF/文件路径")
二.dom4j的常用方法
- selecNodes:获取到元素
selectSingleNode:拿到单个元素
getRootElement():拿到根元素
attributeValue:只有元素才可以点出这个方法来获取值
getText:拿到元素文本
三.解析XML文件
- 我们去配置位置及读取xml配置文件时,需要将图片下方这些jar包导入。
- xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE config[
<!ELEMENT config (action*)>
<!ELEMENT action (forward*)>
<!ELEMENT forward EMPTY>
<!ATTLIST action
path CDATA #REQUIRED
type CDATA #REQUIRED
>
<!ATTLIST forward
name CDATA #REQUIRED
path CDATA #REQUIRED
redirect (true|false) "false"
>
]>
<config>
<action path="/studentAction" type="org.lisen.mvc.action.StudentAction">
<forward name="students" path="/students/studentList.jsp" redirect="false"/>
</action>
<action path="/bookAction" type="org.lisen.mvc.action.bookAction">
<forward name="books" path="/books/bookList.jsp" redirect="false"/>
</action>
</config>
- 解析xml文件操作
-
package com.yjx.test; import java.io.InputStream; import java.util.Iterator; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class XmlRead { public static void main(String[] args) throws Exception { //读取xml文件 InputStream in=XmlRead.class.getResourceAsStream("config.xml"); SAXReader reads=new SAXReader(); //读取该文件得到一个文档 Document doc=reads.read(in); //得到元素 Element el=doc.getRootElement(); //获取到action该节点 List<Element> action=el.selectNodes("action"); for (Element e : action) { //获取到action元素的 String path=e.attributeValue("path"); String type=e.attributeValue("type"); System.out.println(path); System.out.println(type); //在获取到action下的节点forward List<Element> forward=e.selectNodes("forward"); for(Element f:forward) { //获取到forward节点的属性 String name=f.attributeValue("name"); String path01=f.attributeValue("path"); String redirect=f.attributeValue("redirect"); System.out.println(name); System.out.println(path01); System.out.println(redirect); } } } }
今天的学习就到这里啦!!!