使用 Java 解析 XML 文件有许多成熟的工具,如 dom4j 等等。但在一些场景中,我们可能使用 Ant、Maven 等构建工具对多个 XML 文件进行合并,我们希望可以直接通过脚本文件,或者简单的程序就能完成这样的功能,那么使用 XSL 是一个非常不错的选择。本文将介绍通过简单的 Java 程序加上 XSL 文件来完成多个 XML 文件的合并操作。(XSL 是一种样式表语言,可用以描述如何显示一个 XML 文件)
背景:
Config.xml 文件的结构与 FinalConfig.xml 文件相似;
需要将 Config.xml 文件的内容合并到 FinalConfig.xml 文件;
若 FinalConfig.xml 文件中已存在 Config.xml 的内容,则覆盖。
目标:程序执行完成后,生成一个唯一的 XML 文件 FinalConfig.xml;
FinalConfig.xml 文件结构:
1
2
3
4 100
5 Fly to the Moon
6 This is Fly to the Moon
7
8
9 101
10 10 Miles
11 This is 10 Miles
12
13
14
Config.xml 文件结构:
1
2
3
4 100
5 Fly to the Sun
6 This is Fly to the Sun
7
8
9
我们假定 gameid 是固定值,不会变。在合并完成后,为 100 的 node 被更新。希望得到新的 FinalConfig.xml 文件如下:
1
2
3
4 100
5 Fly to the Sun
6 This is Fly to the Sun
7
8
9 101
10 10 Miles
11 This is 10 Miles
12
13
14
一、Java 调用程序
1 private voidmergeXml(File xslFile, File configXml, File finalConfigXml){2 DocumentBuilderFactory dbFac =DocumentBuilderFactory.newInstance();3 DocumentBuilder builder;4 Document destDoc = null;5 FileInputStream input;6 try{7 builder =dbFac.newDocumentBuilder();8 destDoc =builder.parse(finalConfigXml);9 if(!finalConfigXml.exists())10 {11 finalConfigXml.createNewFile();12 }13 input = newFileInputStream(xslFile);14 StreamSource source = newStreamSource(input);15 Transformer transformer =TransformerFactory.newInstance().newTransformer(source);16 //为xsl文件设置变量"configXmlPath",将configXml文件的路径传递给xsl
17 transformer.setParameter("configXmlPath", configXml.getPath());18 transformer.transform(new DOMSource(destDoc), newStreamResult(finalConfigXml));19 }catch(Exception e) {20 e.printStackTrace();21 }22 }
二、XSL 文件
1 <?xml version="1.0" encoding="UTF-8"?>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
三、XSL 文件解析
1.Java 传入参数 “configXmlPath” 为 Config.xml 文件的路径
1
2.取出 Config.xml 文件中所有的 gameid,此处为增强处理,即 Config.xml 文件中可以存在多个 节点
1
2
3
4
5
6
7
8
9
3.判断 FinalConfig.xml 的 子节点中是否存在当前的 gameid ,若不存在则复制
1
2
3
4
5
4.复制 Config.xml 文件中的所有 节点
(本文系从原博客迁移至此,并进行部分编辑。原文链接:http://thewaychung.iteye.com/blog/2072740)