1. Use dom4j to parse XML files and dom4j to parse xml files
I.Dom4j Introduction
Dom4j is a Java xml api and a jdom upgrade product used to read and write XML files. Dom4j is a very good JavaXML API with excellent performance, powerful functionality, and extremely easy to use features. Its performance exceeds sun's official dom technology, it is also an open-source software that can be found on SourceForge. You can also find an article on IBM developerWorks to evaluate the performance, functionality, and usability of mainstream Java XML APIs. Therefore, you can know that dom4j is excellent in any aspect. Now we can see that more and more Java software are using dom4j to read and write XML. It is particularly worth mentioning that Sun's JAXM is also using dom4j. This is a required jar package. Hibernate also uses it to read and write configuration files.
2. Simple dom4j parsing 1. Import Maven dependencies of dom4j
<!-- parser xml file --><dependency> <groupId>org.dom4j</groupId> <artifactId>dom4j</artifactId> <version>2.1.0</version></dependency>
2. Create the userConfig. xml file
<?xml version="1.0" encoding="UTF-8"?><users> <user> <userName>user1</userName> <password>123</password> <systemId>AAA</systemId> </user> <user> <userName>user2</userName> <password>456</password> <systemId>BBB</systemId> </user></users>
3. Use the SAXReader class and parse xml files
package com.my.utils;import java.io.File;import java.util.List;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;public class ReadXMLConfig { public static void main(String[] args) { // TODO Auto-generated method stub //define config file path //String path = this.getClass().getClassLoader().getResource("").getPath()+"config/userConfig.xml"; String path = "src/main/resources/config/userConfig.xml"; SAXReader reader = new SAXReader(); reader.setEncoding("utf-8"); Document document = null; try { document = reader.read(new File(path)); Element root = document.getRootElement(); //get user list List<Element> list = root.elements("user"); Element use1 = list.get(0); //get user info System.out.println(use1.element("userName").getStringValue()); System.out.println(use1.element("password").getStringValue()); System.out.println(use1.element("systemId").getStringValue()); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
The input result is as follows:
user1123AAA
For parsing each user info, this is just a simple parsing.
If you have any questions, please leave a message and you will be able to solve them as soon as possible.