利用JDOM把两个XML合并生得到一个Document对象

通常一些应用框架都会用 XML 作为配置,而且很多都支持多个 XML 文件,例如 Struts 框架可以配置多个 struts-config-xxx.xml 文件,Spring 也允许你用多个 applicationContext-xxx.xml 文件,再比如 DWR 也是可以由多个 dwr-xxx.xml 依功能或其他方式分开来配置。我们知道, 这样的多个 XML 有相同的规范定义,那么程序如何一并解析它们呢?我看过 ActionServlet 是对 struts-config-xxx.xml 逐个解析的。 我这里介绍的一种方法是把那些有着相同规范定义的 XML 合成一个 Document 然后对这个 Document 对象进行处理,如 XPath 查找、进行 DOM 对象操作, 就不需要每次到多个 Document 中去查找一遍。


众所周知,对 XML 的操作有两种方式,DOM:XML 映射在内存中一颗树;SAX:基于事件的方式。常用的 XML Java 解析组件有 DOM4J(Apache的)、JDOM、和JAXP(Sun的),它们都提供了 DOM 和 SAX 实现和 Xpath 查找。

下面我就介绍用 JDOM 完成对多个 XML 文件进行合并得到一个 Document 对象,实现代码如下:
 1/*
 2 * Created on Sep 23, 2007
 3 */
 4package com.unmi;
 5
 6import java.io.IOException;
 7import java.util.List;
 8
 9import org.jdom.Document;
10import org.jdom.Element;
11import org.jdom.JDOMException;
12import org.jdom.input.SAXBuilder;
13
14/**
15 * Combine two or more XML together as one document
16 * I put this operation into main method.
17 * @author Unmi
18 */
19public class CombineXML
20{
21
22    /**
23     * @param args
24     * @throws Exception
25     */
26    public static void main(String[] args) throws Exception
27    {
28        Document document = null;
29        try {
30            SAXBuilder dbf = new SAXBuilder();
31            document = (Document) dbf.build(args[0]);
32            Element docRoot = document.getRootElement();
33
34            for (int i = 1; i < args.length; i++) {
35                Document tmpdoc = dbf.build(args[i]);
36                List<Element&gt; nlt = tmpdoc.getRootElement().getChildren();
37                for (int j = 0; j < nlt.size(); ) {
38                    Element el = nlt.get(0);
39                    // get free element
40                    el.detach();
41                    docRoot.addContent(el);
42                }
43            }
44        } catch (IOException e) {
45            throw new Exception("File not readable.");
46        } catch (JDOMException e) {
47            throw new Exception("File parsed error.");
48        }
49
50        //TODO, You can process that document now.
51    }
52}

研究这个的目的是,我想做一个工具合并多个 Struts-config 配置文件,然后输入 nath、nction、norward、name 或 type 等中的一个属性值查找到相关的其他属性值,这样能方便程序调试,比如看到哪个 aciton.do 就知道会转向到哪些个页面,附着了哪个 formbean,以及其他相关的属性值是什么。 永久链接 https://yanbin.blog/jdom-combine-xml-one-document/, 来自 隔叶黄莺 Yanbin's Blog
[版权声明] 本文采用 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 进行许可。