DOM4J is an open source XML parsing package, which is used by many frameworks to parse XML files, such as Mybatis and Spring framework.
Here are the basic uses:
Introduction of depend on
<! - dom4j dependence - >
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<! -- Xpath expression dependencies -->
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
Copy the code
Prepare an XML fileapplicationConfig.xml
<configuration>
<! -- Database configuration information -->
<dataSource>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</configuration>
Copy the code
To parse the XML
public Document parse(a) throws DocumentException {
// Load the configuration file into memory through the class loader
InputStream inputStream = XmlConfigBuilder.class.getClassLoader().getResourceAsStream("applicationConfig.xml");
// Parse the XML file
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
return document;
}
Copy the code
Gets the document root node
Element rootElement = document.getRootElement();
Copy the code
Navigate to specific labels using XPath
XPath is a language for finding information in XML documents. XPath can be used to traverse elements and attributes in AN XML document.
// Read the property tag
List propertyList = rootElement.selectNodes("//property");
Properties properties = new Properties();
for (Object o : propertyList) {
Element element = (Element)o;
// Get tag attributes
String value = element.attributeValue("value");
String name = element.attributeValue("name");
properties.setProperty(name,value);
}
// Convert the property tag content to the DruidDataSource object
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(properties.getProperty("driverClass"));
druidDataSource.setUrl(properties.getProperty("jdbcUrl"));
druidDataSource.setUsername(properties.getProperty("username"));
druidDataSource.setPassword(properties.getProperty("password"));
Copy the code