在利用digester處理XML文件時,讀取多個XML文件,代碼反復(fù)測試都出現(xiàn)錯誤。后來,經(jīng)過幾個分鐘的查找,終于加入一段代碼讓程序跑通。代碼如下:
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的部分代碼,發(fā)現(xiàn)了這個錯誤。網(wǎng)上對這個介紹比較少,可能我這個問題比較弱智吧。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);
}