Spring by parsing XML configuration file, the containers are initialized with the reflection technique.
Environment configuration:
Import package dom4j
<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
Use SAXReader read xml file
- Creating SAXReader
SAXReader reader = new SAXReader();
- Create a xml file resource
URL xmlUrl = XmlReaderTest.class.getClassLoader().getResource("applicationContext.xml");
- The XML files and associated resources SAXReader
Document doc = reader.read(xmlUrl);
- Access XML nodes and node attributes
get the root node (an XML only one root node):
Element rootEle = doc.getRootElement();
Walk the child nodes:
while (iterator.hasNext()) {
parseElement(iterator.next());
}
Gets node attributes:
Iterator<Attribute> attributeIterator = element.attributeIterator();
while (attributeIterator.hasNext()) {
Attribute attribute = attributeIterator.next();
System.out.println(attribute.getName() + ": " + attribute.getValue());
}
Sample code:
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
public class XmlReaderTest {
static void parseElement(Element element) {
System.out.println("标签名:" + element.getName());
System.out.println("属性:");
Iterator<Attribute> attributeIterator = element.attributeIterator();
while (attributeIterator.hasNext()) {
Attribute attribute = attributeIterator.next();
System.out.println(attribute.getName() + ": " + attribute.getValue());
}
List<Element> subElementList = element.elements();
if (subElementList.size() > 0) {
System.out.println("子标签:");
}
for (Element subElement: subElementList) {
parseElement(subElement);
}
}
public static void main(String[] args) throws Exception {
SAXReader reader = new SAXReader();
URL xmlUrl = XmlReaderTest.class.getClassLoader().getResource("applicationContext.xml");
Document doc = reader.read(xmlUrl);
Element rootEle = doc.getRootElement();
System.out.println("root Element: " + rootEle.getName());
Iterator<Element> iterator = rootEle.elementIterator();
while (iterator.hasNext()) {
parseElement(iterator.next());
}
}
}
operation result:
root Element: beans
标签名:bean
属性:
id: userDao
class: com.bailiban.day1.helloworld.dao.impl.UserDaoImpl
标签名:bean
属性:
id: userService
class: com.bailiban.day1.helloworld.service.impl.UserServiceImpl
子标签:
标签名:property
属性:
name: userDao
ref: userDao
标签名:bean
属性:
id: client
class: com.bailiban.day1.helloworld.Client
子标签:
标签名:property
属性:
name: userService
ref: userService