YuFeng

dom4j 解析 XML文件
相关得解析文件与使用文档:本地下载:dom4j&xml$反射.zipschema约束的xml文件,<?xml...
扫描右侧二维码阅读全文
16
2018/12

dom4j 解析 XML文件

相关得解析文件与使用文档:
本地下载:
dom4j&xml$反射.zip
schema约束的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>demo1</servlet-name>
                <servlet-class>cn.yufeng.fanshe.Demo1</servlet-class>
            </servlet>
            
</web-app>

dom4j读取xml文档并且创建相应实例,防止代码硬编码

package cn.yufeng.fanshe;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

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

public class Main {
    public static void main(String[] args) {
        testMethod();
        testFiled();
        testMethod2();
    }

    public static void testMethod() {
        try {
            //1.创建解析器
            SAXReader sr = new SAXReader();
            //2.通过解析器来读取xml文档
            Document document = sr.read("src/cn/yufeng/fanshe/web.xml");
            //3.获取xml文档的根文件
            Element rootElement = document.getRootElement();
            //4.获取类的完整路径名称
            String className = rootElement.element("servlet").elementText("servlet-class");
            //5.将类的二进制码加载到内存
            Class clazz = Class.forName(className);
            //6.通过二进制码获取到这个类的相关方法
            Method method = clazz.getMethod("out", null);
            //7.通过二进制码创建一个新对象
            Object o = clazz.newInstance();
            //8执行方法
            method.invoke(o, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void testMethod2() {
        try {
            SAXReader sr = new SAXReader();
            Document document = sr.read("src/cn/yufeng/fanshe/web.xml");
            Element rootElement = document.getRootElement();
            String className = rootElement.element("servlet").elementText("servlet-class");
            Class clazz = Class.forName(className);
            Demo1 d = (Demo1) clazz.newInstance();
            d.out();
            System.out.println("执行完毕");
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
    
    private static void testFiled() {
        try {
            Class clazz = Class.forName("cn.yufeng.fanshe.Demo1");
            Field filed = clazz.getDeclaredField("num");
            Object object = clazz.newInstance();
            filed.set(object, 789);
            System.out.println(filed.get(object));
        } catch (Exception e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } 
    }
}
Last modification:June 11th, 2019 at 12:29 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment