1. 程式人生 > >使用dom4j 解析xml

使用dom4j 解析xml

package png servle dom4j read .cn cati nbsp test

技術分享

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://www.example.org/web-app_2_5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.example.org/web-app_2_5 web-app_2_5.xsd"
    version="2.5">

    <servlet>
        <servlet-name>MyServlet1</
servlet-name> <servlet-class>cn.itheima.web.servlet1.MyServlet1</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet1</servlet-name> <url-pattern>/myServlet1</url-pattern> </servlet-mapping> <
servlet> <servlet-name>MyServlet2</servlet-name> <servlet-class>cn.itheima.web.servlet1.MyServlet2</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet2</servlet-name> <url-pattern>/myServlet2</
url-pattern> </servlet-mapping> </web-app>

TestDom4j.java

package cn.itheima.xml.dom4j;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

public class TestDom4j {
    @Test
    public void testReadWebXML() {
        try {
            // 1.獲取解析器
            SAXReader saxReader = new SAXReader();
            // 2.獲得document文檔對象
            Document doc = saxReader.read("src/cn/itheima/xml/schema/web.xml");
            // 3.獲取根元素
            Element rootElement = doc.getRootElement();
            // System.out.println(rootElement.getName());//獲取根元素的名稱
            // System.out.println(rootElement.attributeValue("version"));//獲取根元素中的屬性值
            // 4.獲取根元素下的子元素
            List<Element> childElements = rootElement.elements();
            // 5.遍歷子元素
            for (Element element : childElements) {
                //6.判斷元素名稱為servlet的元素
                if ("servlet".equals(element.getName())) {
                    //7.獲取servlet-name元素
                    Element servletName = element.element("servlet-name");
                    //8.獲取servlet-class元素
                    Element servletClass = element.element("servlet-class");
                    System.out.println(servletName.getText());
                    System.out.println(servletClass.getText());
                }
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

}

使用dom4j 解析xml