在利用digester处理XML文件时,读取多个XML文件,代码反复测试都出现错误。后来,经过几个分钟的查找,终于加入一段代码让程序跑通。代码如下:
package com.example.demo2;
import java.io.File;
import org.apache.commons.digester.Digester;
public class DigesterDriver {
public static void main(String[] args) {
try {
Digester digester = new Digester();
File input = new File("E:\\MyProjects\\Workspace\\DigesterDemo\\src\\com\\example\\demo2\\example.xml");
File input2 = new File("E:\\MyProjects\\Workspace\\DigesterDemo\\src\\com\\example\\demo2\\example2.xml");
Catalog2 c = new Catalog2();
digester.push(c);
digester.setValidating(false);
digester.addObjectCreate("catalog/hi/book", Book2.class);
digester.addBeanPropertySetter("catalog/hi/book/author", "author");
digester.addBeanPropertySetter("catalog/hi/book/title", "title");
digester.addSetNext("catalog/hi/book", "addBook" );
digester.parse(input);
digester.push(c);
digester.parse(input2);
System.out.println(c.getBooks().size());
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
其中,红色部分是后来加入的,仔细阅读了struts的部分代码,发现了这个错误。网上对这个介绍比较少,可能我这个问题比较弱智吧。struts的代码片段如下:
// Configure the Digester instance we will use
Digester digester = initConfigDigester();
// Process each specified resource path
while (paths.length() > 0) {
digester.push(config);
String path = null;
int comma = paths.indexOf(',');
if (comma >= 0) {
path = paths.substring(0, comma).trim();
paths = paths.substring(comma + 1);
} else {
path = paths.trim();
paths = "";
}
if (path.length() < 1) {
break;
}
this.parseModuleConfigFile(prefix, paths, config, digester, path);
}