Day1 Java读取XML文件

Spring通过解析XML配置文件,利用反射技术对容器进行初始化。

环境配置:
导入dom4j包



    dom4j
    dom4j
    1.6.1

使用SAXReader读取xml文件

  1. 创建SAXReader SAXReader reader = new SAXReader();
  2. 创建xml文件资源 URL xmlUrl = XmlReaderTest.class.getClassLoader().getResource("applicationContext.xml");
  3. 将SAXReader和XML文件资源关联 Document doc = reader.read(xmlUrl);
  4. 访问XML节点和节点属性
    获取根节点(一个XML只有一个根节点):
Element rootEle = doc.getRootElement();

遍历子节点:

while (iterator.hasNext()) {
     parseElement(iterator.next());
}

获取节点属性:

Iterator attributeIterator = element.attributeIterator();
   while (attributeIterator.hasNext()) {
      Attribute attribute = attributeIterator.next();
      System.out.println(attribute.getName() + ": " + attribute.getValue());
}

示例代码:

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 attributeIterator = element.attributeIterator();
        while (attributeIterator.hasNext()) {
            Attribute attribute = attributeIterator.next();
            System.out.println(attribute.getName() + ": " + attribute.getValue());
        }
        List 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 iterator = rootEle.elementIterator();
        while (iterator.hasNext()) {
            parseElement(iterator.next());
        }
    }
}

运行结果:

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

你可能感兴趣的:(Day1 Java读取XML文件)