当我们开发一些程序的时候,可能会自定义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());
}
}
运行结果如下: