一、依赖
<dependency> <groupId>org.dom4j</groupId> <artifactId>dom4j</artifactId> <version>2.1.3</version> <scope>compile</scope> </dependency>
二、XML样例文件
<mymvc> <actions> <action name="list" class="controller.List"> <result name="toListJSP"> /list.jsp </result> <result name="toShowUserinfoList" type="'redirect"> showUserinfoList.ghy </result> </action> <action name="showUserinfoList" class="controller.ShowUserinfoList"> <result name="toShowUserinfoListJSP"> /showUserinfoList.jsp </result> </action> </actions> </mymvc>
三、读取XML文件
import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.util.List; public class Reader { public static void main(String[] args) throws DocumentException { SAXReader reader=new SAXReader(); //1、读取XML文件 Document document = reader.read(reader.getClass().getResourceAsStream("/struts.xml")); //2、获取根元素 Element rootElement = document.getRootElement(); //打印根元素名字 System.out.println("根元素名字:"+rootElement.getName()); //获取指定元素 Element actions = rootElement.element("actions"); System.out.println("actions:"+actions.getName()); //获取根元素的所有子元素 List<Element> rootChildren = rootElement.elements(); for (Element child : rootChildren) { System.out.println("子元素名字:"+child.getName()); List<Element> childChildren = child.elements(); if (childChildren!=null&&childChildren.size()>0) { for (Element childChild : childChildren) { //获取子元素名字 System.out.println("子元素-子元素名字:"+childChild.getName()); System.out.println("子元素-子元素name属性"+childChild.attribute("name").getValue()); List<Attribute> attributes = childChild.attributes(); if (attributes!=null&&attributes.size()>0) { for (Attribute attribute : attributes) { System.out.println("子元素-子元素属性名字:"+attribute.getName()+"子元素-子元素属性值:"+attribute.getValue()); } } List<Element> elements = childChild.elements(); if (elements!=null&&elements.size()>0) { for (Element element : elements) { //获取元素值 System.out.println(element.getTextTrim()); } } } } } } }
根元素名字:mymvc actions:actions 子元素名字:actions 子元素-子元素名字:action 子元素-子元素name属性list 子元素-子元素属性名字:name子元素-子元素属性值:list 子元素-子元素属性名字:class子元素-子元素属性值:controller.List /list.jsp showUserinfoList.ghy 子元素-子元素名字:action 子元素-子元素name属性showUserinfoList 子元素-子元素属性名字:name子元素-子元素属性值:showUserinfoList 子元素-子元素属性名字:class子元素-子元素属性值:controller.ShowUserinfoList /showUserinfoList.jsp