dom4j 的使用与 模拟Spring中的 IOC 容器实现

虽然现在 JSON 大法贼好,但是有时候你需要调用的接口还是 xml 格式的奥,所以这边写一下 dom4j 的使用,(emmmmmm 公司墙很高,只让用 CSDN,你猜是哪家)。

这边我使用 maven 构建工程
在这里插入图片描述
找到 pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>studyDom4j</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>studyDom4j</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.7</version>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-core</artifactId>
      <version>1.1.7</version>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-access</artifactId>
      <version>1.1.7</version>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.1.7</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
    <dependency>
      <groupId>dom4j</groupId>
      <artifactId>dom4j</artifactId>
      <version>1.6.1</version>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>


这里还用了日志工具 sfl4j + logback

<!-- 级别从高到低 OFF 、 FATAL 、 ERROR 、 WARN 、 INFO 、 DEBUG 、 TRACE 、 ALL -->
<!-- 日志输出规则 根据当前ROOT 级别,日志输出时,级别高于root默认的级别时 会输出 -->
<!-- 以下 每个配置的 filter 是过滤掉输出文件里面,会出现高级别文件,依然出现低级别的日志信息,通过filter 过滤只记录本级别的日志 -->
<!-- scan 当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true。 -->
<!-- scanPeriod 设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。 -->
<!-- debug 当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
    <!-- 动态日志级别 -->
    <jmxConfigurator />
    <!-- 定义日志文件 输出位置 -->
    <!-- <property name="log_dir" value="C:/test" />-->
    <property name="log_dir" value="./log" />
    <!-- 日志最大的历史 30天 -->
    <property name="maxHistory" value="30" />

    <!-- ConsoleAppender 控制台输出日志 -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>
                <!-- 设置日志输出格式 -->
                %d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%n
            </pattern>
        </encoder>
    </appender>

    <!-- ERROR级别日志 -->
    <!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 RollingFileAppender -->
    <appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!-- 过滤器,只记录WARN级别的日志 -->
        <!-- 果日志级别等于配置级别,过滤器会根据onMath 和 onMismatch接收或拒绝日志。 -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <!-- 设置过滤级别 -->
            <level>ERROR</level>
            <!-- 用于配置符合过滤条件的操作 -->
            <onMatch>ACCEPT</onMatch>
            <!-- 用于配置不符合过滤条件的操作 -->
            <onMismatch>DENY</onMismatch>
        </filter>
        <!-- 最常用的滚动策略,它根据时间来制定滚动策略.既负责滚动也负责出发滚动 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志输出位置 可相对、和绝对路径 -->
            <fileNamePattern>
                ${log_dir}/error/%d{yyyy-MM-dd}/error-log.log
            </fileNamePattern>
            <!-- 可选节点,控制保留的归档文件的最大数量,超出数量就删除旧文件假设设置每个月滚动,且<maxHistory>是6, 则只保存最近6个月的文件,删除之前的旧文件。注意,删除旧文件是,那些为了归档而创建的目录也会被删除 -->
            <maxHistory>${maxHistory}</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>
                <!-- 设置日志输出格式 -->
                %d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%n
            </pattern>
        </encoder>
    </appender>

    <!-- WARN级别日志 appender -->
    <appender name="WARN" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!-- 过滤器,只记录WARN级别的日志 -->
        <!-- 果日志级别等于配置级别,过滤器会根据onMath 和 onMismatch接收或拒绝日志。 -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <!-- 设置过滤级别 -->
            <level>WARN</level>
            <!-- 用于配置符合过滤条件的操作 -->
            <onMatch>ACCEPT</onMatch>
            <!-- 用于配置不符合过滤条件的操作 -->
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志输出位置 可相对、和绝对路径 -->
            <fileNamePattern>${log_dir}/warn/%d{yyyy-MM-dd}/warn-log.log</fileNamePattern>
            <maxHistory>${maxHistory}</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- INFO级别日志 appender -->
    <appender name="INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log_dir}/info/%d{yyyy-MM-dd}/info-log.log</fileNamePattern>
            <maxHistory>${maxHistory}</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- DEBUG级别日志 appender -->
    <appender name="DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>DEBUG</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log_dir}/debug/%d{yyyy-MM-dd}/debug-log.log</fileNamePattern>
            <maxHistory>${maxHistory}</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- TRACE级别日志 appender -->
    <appender name="TRACE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>TRACE</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log_dir}/trace/%d{yyyy-MM-dd}/trace-log.log</fileNamePattern>
            <maxHistory>${maxHistory}</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- root级别 DEBUG -->
    <root>
        <!-- 打印debug级别日志及以上级别日志 -->
        <level value="debug" />
        <!-- 控制台输出 -->
        <appender-ref ref="console" />
        <!-- 文件输出 -->
        <appender-ref ref="ERROR" />
        <appender-ref ref="INFO" />
        <appender-ref ref="WARN" />
        <appender-ref ref="DEBUG" />
        <appender-ref ref="TRACE" />
    </root>
</configuration>

然后就可以开启 dom4j 玩转 xml 大法了。

使用 InputStream 从本地读 xml 文件进行解析
package org.example;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * Hello world!
 *
 */
public class App 
{
    private static Logger logger = LoggerFactory.getLogger(App.class);
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
        try {
            useInputStreamOperaXML();
        }catch (FileNotFoundException | DocumentException e){
            e.printStackTrace();
        }

    }

    /**
     * 使用 InputStream 从本地读 xml 文件进行解析
     */
    private static void useInputStreamOperaXML() throws FileNotFoundException, DocumentException {
        logger.info("使用 InputStream 从本地读 xml 文件进行解析 start");
        SAXReader reader = new SAXReader();
        File file = new File("book.xml");
        if(file.exists()){
            InputStream in = new FileInputStream(file);
            Document document = reader.read(file);
            logger.info(document.asXML());
        }
        logger.info("使用 InputStream 从本地读 xml 文件进行解析 end");

    }
}

输出

2020-04-14 21:39:05.491 INFO  org.example.App - 使用 InputStream 从本地读 xml 文件进行解析 start
2020-04-14 21:39:05.586 INFO  org.example.App - <?xml version="1.0" encoding="UTF-8"?>
<books>
    <books id="book1" date="2020">
        <author>腾讯</author>
        <category>产品</category>
    </books>
    <books id="book1" date="2020">
        <author>阿里</author>
        <category>运营</category>
    </books>
    <books id="book1" date="2020">
        <author>华为</author>
        <category>技术</category>
    </books>
</books>
2020-04-14 21:39:05.587 INFO  org.example.App - 使用 InputStream 从本地读 xml 文件进行解析 end
通过DocumentHelper创建(解析)一个Document对象,并为Document添加元素
/**
     * 通过DocumentHelper创建(解析)一个Document对象,并为Document添加元素
     */
    private static void useDocumentCreateXML() {
        logger.info("----------- org.example.App.useDocumentCreateXML start");
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");
        Element p1 =root.addElement("person")
                    .addAttribute("age", "18")
                .addText("张三");
        Element p2 =root.addElement("person")
                .addAttribute("age", "19")
                .addText("李四");
        Element p3 =root.addElement("person")
                .addAttribute("age", "20")
                .addText("王五");
        logger.info(document.asXML());
        logger.info("----------- org.example.App.useDocumentCreateXML end");

    }

输出

2020-04-14 21:51:06.405 INFO  org.example.App - ----------- org.example.App.useDocumentCreateXML start
2020-04-14 21:51:06.406 INFO  org.example.App - <?xml version="1.0" encoding="UTF-8"?>
<root><person age="18">张三</person><person age="19">李四</person><person age="20">王五</person></root>
2020-04-14 21:51:06.406 INFO  org.example.App - ----------- org.example.App.useDocumentCreateXML end
解析XML字符串获取Document对象 public static Document parseText(String text) throws DocumentException {…}
 private static void useDocumentParseText() throws DocumentException {
        logger.info("----------- org.example.App.useDocumentParseText start");
        Document document = DocumentHelper.parseText("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<root><person age=\"18\">张三</person><person age=\"19\">李四</person><person age=\"20\">王五</person></root>");
        logger.info(document.asXML());
        logger.info("----------- org.example.App.useDocumentParseText end");
    }

输出

2020-04-14 22:06:04.718 INFO  org.example.App - ----------- org.example.App.useDocumentParseText start
2020-04-14 22:06:04.759 INFO  org.example.App - <?xml version="1.0" encoding="UTF-8"?>
<root><person age="18">张三</person><person age="19">李四</person><person age="20">王五</person></root>
2020-04-14 22:06:04.759 INFO  org.example.App - ----------- org.example.App.useDocumentParseText end
模拟SpringIOC 依赖注入机制(通过反射实现),有如下spring_core.xml配置,主要使用了反射机制

首先在项目当前目录中创建 spring-ioc.xml 文件模拟

<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <bean id="testBean" class="com.just.Test"/>
</beans>
 // 模拟SpringIOC 依赖注入机制(通过反射实现),有如下spring_core.xml配置,主要使用了反射机制
    private static void simulateIOC() throws FileNotFoundException, DocumentException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        logger.info("----------- org.example.App.simulateIOC start");
        SAXReader reader = new SAXReader();
        // File file =new File("logback.xml");
        File file = new File("spring-ioc.xml");
        if(file.exists()){
            InputStream in = new FileInputStream(file);
            Document document = reader.read(in);
            logger.info(document.asXML());
            Element root = document.getRootElement();
            Element foo;
            for (Iterator i = root.elementIterator("bean"); i.hasNext();){
                foo = (Element) i.next();
                //针对每一个bean实例获取id和name属性
                Attribute id = foo.attribute("id");
                Attribute clazz = foo.attribute("class");

                //利用反射,通过class名称获取class对象
                Class bean = Class.forName(clazz.getText());
                Object object = bean.newInstance();
                Method method = bean.getMethod("sayHello");
                Object result = method.invoke(object);
                logger.info(result.toString());
                // other 省略无关的反射操作
            }

            logger.info("----------- org.example.App.simulateIOC end");

        }
    }

输出

2020-04-14 22:55:43.869 INFO  org.example.App - ----------- org.example.App.simulateIOC start
2020-04-14 22:55:43.919 INFO  org.example.App - <?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="testBean" class="org.example.HelloWorld"/>
</beans>
2020-04-14 22:55:43.921 INFO  org.example.App - hello
2020-04-14 22:55:43.923 INFO  org.example.App - ----------- org.example.App.simulateIOC end
将Document写出
 // 将 document对象 输出为xml文件
    private static void outPutDocumentXML() throws Exception {
        logger.info("----------- org.example.App.outPutDocumentXML start");
        String xmlStr = "<books>"
                + "<book><title>AAA</title><author>aaa</author></book>"
                + "<book><title>BBB</title><author>bbb</author></book>"
                + "<book><title>CCC</title><author>ccc</author></book>"
                + "</books>";
        // 解析字符串获取document对象
        Document document = DocumentHelper.parseText(xmlStr);
        //设置输出样式(整洁)
        OutputFormat format = OutputFormat.createPrettyPrint();
        // 将document写出到output.xml中,并指定输出样式
        XMLWriter writer = new XMLWriter(new FileOutputStream("output.xml"),format);
        writer.write(document);
        // 使用pretty(整洁)样式输出到控制台
        writer = new XMLWriter(System.out, format);
        writer.write(document);
        System.out.println("--------------------------------------------------------------");
        // 使用紧凑样式输出到控制台
        format = OutputFormat.createCompactFormat();
        writer = new XMLWriter(System.out, format);
        writer.write(document);
        logger.info("----------- org.example.App.outPutDocumentXML end");
    }

输出

2020-04-14 22:59:59.308 INFO  org.example.App - ----------- org.example.App.outPutDocumentXML start
<?xml version="1.0" encoding="UTF-8"?>

<books>
  <book>
    <title>AAA</title>
    <author>aaa</author>
  </book>
  <book>
    <title>BBB</title>
    <author>bbb</author>
  </book>
  <book>
    <title>CCC</title>
    <author>ccc</author>
  </book>
</books>
--------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<books><book><title>AAA</title><author>aaa</author></book><book><title>BBB</title><author>bbb</author></book><book><title>CCC</title><author>ccc</author></book></books>2020-04-14 22:59:59.350 INFO  org.example.App - ----------- org.example.App.outPutDocumentXML end

源码地址: https://github.com/weijieqiu/iStudy/tree/master/studyDom4j/studyDom4j

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值