dom4j对多个xml进行合并

当我们开发一些程序的时候,可能会自定义xml来对程序进行配置,但是只使用单个xml来配置可能会遇到一个问题,到后期有可能xml配置文件越来越大越来越长,比较难以维护,那就可以将单个xml文件按照情况进行拆分,启动的时候再将其合并。

注意如果有特殊字符用CDATA包装下,不然会初始化抛出异常(如下):

<a>
    <![CDATA[这是有特殊字符的&一句话]]>
</a>

比如,有个配置的xml:

<?xml version="1.0" encoding="UTF-8"?>
<tube-router>
    <other>xxx</other>
    <flows>
    ........
    </flows>
</tube-router>

其中在flows中可能有很多个flow节点,并且每个flow节点都很多内容,试想一下当flow很多个的时候那么就会让这个xml文件很难阅读,那么我们可以将里面的flow节点单独的配置出来。

如下:

<?xml version="1.0" encoding="UTF-8"?>
<tube-router>
    <flow>flow02</flow>
</tube-router>

在程序启动的时候将上面的两个xml进行合并:

<?xml version="1.0" encoding="UTF-8"?>
<tube-router>
    <other>xxx</other>
    <flows>
        <flow>flow02</flow>
    </flows>
</tube-router>

下面是一个demo:

这里写图片描述

将上面的flow01.xml和flow02.xml合并到root.xml中

xml里面的内容:

//flow01.xml
<?xml version="1.0" encoding="UTF-8"?>
<tube-router>
    <flow>flow01</flow>
</tube-router>

//flow02.xml
<?xml version="1.0" encoding="UTF-8"?>
<tube-router>
    <flow>flow02</flow>
</tube-router>

//root.xml
<?xml version="1.0" encoding="UTF-8"?>
<tube-router>
    <other>xxx</other>
    <flows></flows>
</tube-router>

MainClass类:

public class MainClass {
    public static void main(String[] args) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        String classpath = MainClass.class.getResource("/").getPath();
        String tube = classpath + File.separator + "root.xml";
        Document rootDoc = saxReader.read(new File(tube));
        Element parent = rootDoc.getRootElement();
        Element flows = parent.element("flows");
        File file = new File(classpath);
        if (file.exists()) {
            File[] files = file.listFiles(new FileFilter() {
                public boolean accept(File pathname) {
                    String fileName = pathname.getName();
                    String pattern = "^flow.*.xml$";
                    boolean matches = Pattern.matches(pattern, fileName);
                    return matches;
                }
            });
            for (File f : files) {
                Document read = saxReader.read(f);
                List<Element> elements = read.getDocument().getRootElement().elements();
                for (Element emt : elements) {
                    flows.add(emt.detach());
                }
            }
        }
        System.out.println(rootDoc.asXML());
    }
}

运行结果如下:

这里写图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值