dom4j操作xml

关于xml的schema约束,参考:

https://www.cnblogs.com/wenbronk/p/5786009.html

 

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>helloServlet</servlet-name>
        <servlet-class>hello</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>helloServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

 

引入dom4j 

https://dom4j.github.io/

引入jaxen

http://www.java2s.com/Code/Jar/j/Downloadjaxen112jar.htm

测试:

package cn.sasa.xmltest;

import java.util.List;

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

public class TestDom4j {

    public static void main(String[] args) {
        //获取解析器
        SAXReader reader = new SAXReader();
        try {
            //获取document
            Document doc = reader.read("src/cn/sasa/xmltest/web.xml");
            //获取根节点
            Element element = doc.getRootElement();
//            System.out.println(element.getName());
//            System.out.println(element.attributeValue("version"));
            //获取子元素
            List<Element> chilList = element.elements();
            for(Element e : chilList) {
                //System.out.println(e.getName());
                if("servlet".equals(e.getName())) {
                    Element eName = e.element("servlet-name");
                    Element eClass = e.element("servlet-class");
                    System.out.println(eName.getName()+":"+eName.getText());
                    System.out.println(eClass.getName()+":"+eClass.getText());
                }
            }
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 

posted @ 2019-03-21 14:54  SasaL  Views(195)  Comments(0Edit  收藏  举报