digester解析xml

Digester

Digester 框架是以模式( Pattern )和规则( Rule )为基础处理输入的 XML 。

下面以实例说明:

写道
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.digester.Digester;
import org.xml.sax.SAXException;

public class DigesterDriver {

private static DigesterDriver digesterDriver = null;

private static ClientConfig clientConfig = new ClientConfig();

private DigesterDriver() {
// TODO Auto-generated constructor stub
}

public static DigesterDriver getInstance(){

if(digesterDriver != null){
return digesterDriver;
}
digesterDriver = new DigesterDriver();
Digester digester = new Digester();
digester.setValidating(false);
digester.push(digesterDriver);

digester.addObjectCreate("Config/ClientConfig", ClientConfig.class);
digester.addBeanPropertySetter("Config/ClientConfig/Ip", "ip");
digester.addBeanPropertySetter("Config/ClientConfig/Port","port");
digester.addSetNext("Config/ClientConfig", "setClientConfig");


try {
ClassLoader loader = DigesterDriver.class.getClassLoader();
InputStream inputStream = loader.getResourceAsStream("com/lhy/config.xml");
digesterDriver = (DigesterDriver) digester.parse(inputStream);
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
digesterDriver = null;
e.printStackTrace();
} catch (SAXException e) {
digesterDriver = null;
// TODO Auto-generated catch block
e.printStackTrace();
}

return digesterDriver;
}

public static ClientConfig getClientConfig() {
return clientConfig;
}

public static void setClientConfig(ClientConfig clientConfig) {
DigesterDriver.clientConfig = clientConfig;
}

}

 

代码在附件中---

 

你可能感兴趣的:(解析xml)