目录
dom4j(jar架包)的使用以及使用常用方法获取xml文件中元素和属性
2.1.selectNodes(获取多个元素,小编用来获取根元素)
一:解析思维导图:
二:首先你需要配置好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标签:可以包含0~N个action标签 --> <config> <!-- action标签:可以饱含0~N个forward标签 path:以/开头的字符串,并且值必须唯一 非空 type:字符串,非空 --> <action path="/regAction" type="test.RegAction"> <!-- forward标签:没有子标签; name:字符串,同一action标签下的forward标签name值不能相同 ; path:以/开头的字符串 redirect:只能是false|true,允许空,默认值为false --> <forward name="failed" path="/reg.jsp" redirect="false" /> <forward name="success" path="/login.jsp" redirect="true" /> </action> <action path="/loginAction" type="test.LoginAction"> <forward name="failed" path="/login.jsp" redirect="false" /> <forward name="success" path="/main.jsp" redirect="true" /> </action> </config>
三:获取java中配置文件的三种配置位置以及读取方式:
1.在同包的情况下:
Demo1.class.getResourceAsStream("config.xml");
2.根路径的情况下:
Demo1.class.getResourceAsStream("/config.xml");
根路径的查看方法:
右击项目之后,点击下图中蓝色区域:
进入下图界面,选择Source就可以看到resources和src时同一目录下,小编将config文件放在了resource目录下,所以可以使用根目录的方法获取文件
3.WIN-INF安全路径:
context.getResourceAsStream("/WEB-INF/config");
dom4j(jar架包)的使用以及使用常用方法获取xml文件中元素和属性
1.架包获取
所用jar包 dom4j
架包下载
xml解析架包 密码:hlx8
2.常用方法
2.1.selectNodes(获取多个元素,小编用来获取根元素)
//获取根元素 Element rootElement = doc.getRootElement();
2.2.selectSingleNode(获取单个元素)
//获取单个元素 Element rootElement = doc.selectSingleNode();
2.3.attributeValue(获取元素中的属性)
String path = action.attributeValue("path"); String type = action.attributeValue("type");
2.4.getText(获取属性中的值)
String path = action.getText();
3.源代码:
package com.zking.mvc; 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; public class XmlRead { public static void main(String[] args) throws Exception { //通过流的方式,获取文件 InputStream in = XmlRead.class.getResourceAsStream("/config.xml"); //读取xml文件,并且帮我们进行解析 SAXReader reader = new SAXReader(); //读取之后放到doc中 Document doc = reader.read(in); //获取根元素 Element rootElement = doc.getRootElement(); List<Element> actions = rootElement.selectNodes("/config/action"); //循环遍历获取action下的属性 for (Element action : actions) { String path = action.attributeValue("path"); String type = action.attributeValue("type"); List<Element> forwards = action.selectNodes("forward"); //循环遍历获取forward下的属性 for (Element forward : forwards) { String name = forward.attributeValue("name"); String fpath = forward.attributeValue("path"); String redirect = forward.attributeValue("redirect"); System.out.println("name = " + name); System.out.println("fpath = " + fpath); System.out.println("redirect = " + redirect); } System.out.println("path = " + path); System.out.println("type = " + type); System.out.println("================="); } } }