多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
首先创建 **.xml** 文件,内容如下; ``` <?xml version="1.0" encoding="utf-8" ?> <!--我是注释标签--> <stus> <stu id="18"> <name>我是xml</name> <age>20</age> <address>Beijing</address> </stu> <stu id="12"> <name>我是xml的滴滴</name> <age>19</age> <address>ShangHai</address> <!-- &lt;!&ndash; https://mvnrepository.com/artifact/dom4j/dom4j &ndash;&gt;--> <!-- <dependency>--> <!-- <groupId>dom4j</groupId>--> <!-- <artifactId>dom4j</artifactId>--> <!-- <version>1.6.1</version>--> <!-- </dependency>--> </stu> <stu id="13"> <name>I`m jack</name> <age>24</age> <address>Tianjin</address> </stu> </stus> ``` 我们要获取每个stu里面的元素内容,节点开始是`<stus>` 终点是`</stus>` 首先要获取一个操作解析xml文件的对象,其次通过对象获取到获取到方法类,然后通过方法类获取到起点标签,然后.....以此类推 **代码实现:** ``` package day05; import org.apache.log4j.Logger; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.io.File; import java.util.List; public class day01xmlmathch { //Logger.getLogger(Tester.class),根据log4j.properties文件的配置去创建一个Tester类(当前类的字节码对象)的日志对象 private static Logger logger = Logger.getLogger(day01xmlmathch.class); public static void main(String args[]) throws Exception { String xmlpath = "src/day05/day01xml.xml"; parsingxml(xmlpath); } // throws是主动抛出异常 public static void parsingxml(String xmlpath) throws Exception { // 获得SaxReader解析器对象 SAXReader saxread = new SAXReader(); // 获得document对象 // 这里的Document用的是org.dom4j里面的 Document document = saxread.read(new File(xmlpath)); // 获得根元素 Element Elementroot = document.getRootElement(); // 获得根元素下的子元素 List<Element> elemlists = Elementroot.elements("stu"); // elements返回的是一个list集合 int num = 0; for(Element element : elemlists){ num++; System.out.println("Processing the 【"+ num +"】 element"); Element nameElem = element.element("name"); Element ageElem = element.element("age"); Element address = element.element("address"); // 获取元素里面的内容 String name = nameElem.getText(); logger.info(name); String age = ageElem.getText(); logger.info(age); String addresselm = address.getText(); logger.info(addresselm); System.out.println("name = " + name + "\nage = " + age + "\naddress = " + addresselm); } } } ``` **运行结果:** Processing the 【1】 element name = 我是xml age = 20 address = Beijing Processing the 【2】 element name = 我是xml的滴滴 age = 19 address = ShangHai Processing the 【3】 element name = I`m jack age = 24 address = Tianjin Process finished with exit code 0