目录
解析XML文件的主流技术包括:DOM、JDOM、SAX、DOM4J;
Java中配置文件的三种配置位置及读取方式
1.同包:
InputStream in = XmlReader.class.getResourceAsStream("config.xml");
2.跟路径:
InputStream in = XmlReader.class.getResourceAsStream("/config.xml");
3.WIN-INF安全路径:
InputStream in = XmlReader.class.getResourceAsStream("WIN-INF/config.xml");
解析XML文件的主流技术包括:DOM、JDOM、SAX、DOM4J;
这里我们使用的是DOM4J,这是一个非常优秀的开源框架(易用、开源)。使用比较广泛。在使用的过程中、只需要通过查询帮助文档即可完成常规的操作。【当XML文档较大的且不考虑平台移植性时,建议采用DOM4J】
dom4j常用的方法:
方法 | 描述 |
selectNodes() | 拿到多个节点 |
selectSingleNode() | 拿到单个节点 |
attributeValue() | 返回指定的属性值,如果属性不存在就返回空字符串 |
getText() | 拿到文本元素 |
getRootElement() | 拿到根元素 |
xpath的对照表
表达式 | 描述 |
// | 表示返回XML文档中的所有符合查找准则的元素,而忽略文档中元素的位置级别 |
/ | 表示绝对路径 |
News/Links/name | 表示相对路径 |
./ | 表示当前节点 |
../ | 表示父节点 |
* | 表示所有元素 |
示例:选择一个名为rollno为‘493’值的属性的学生元素
//student[@rollno='493']
案例
配置(导入jar包):
xml配置文件config.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>
</config>
xml解析代码:
package com.ljq.mymvc.XmlReader;
import java.io.InputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
* XML解析
*
* @author 一麟
*
*/
public class XmlReader {
public static void main(String[] args) throws Exception {
InputStream in = XmlReader.class.getResourceAsStream("/config.xml");
SAXReader sax = new SAXReader();
Document doc = sax.read(in);
// 获取根元素
Element rootElement = doc.getRootElement();
List<Element> actions = rootElement.selectNodes("action");
for (Element e : actions) {
String path = e.attributeValue("path");
String type = e.attributeValue("type");
System.out.println("action path = " + path);
System.out.println("action type = " + type);
List<Element> forwards = e.selectNodes("forward");
for (Element f : forwards) {
String name = f.attributeValue("name");
String fpath = f.attributeValue("path");
String redirect = f.attributeValue("redirect");
System.out.println("forward name = " + name);
System.out.println("forward fpath = " + fpath);
System.out.println("forward redirect = " + redirect);
}
System.out.println("=====================");
}
}
}
输出结果如下: