digester实例

来源:互联网 发布:python 时间戳 小数点 编辑:程序博客网 时间:2024/05/04 17:24
import java.io.IOException;import java.net.URL;import org.apache.commons.digester.Digester;import org.apache.commons.digester.xmlrules.DigesterLoader;import org.xml.sax.SAXException;public class XmlParser{    private Object object;    public Object parseXml2Bean(String xmlPath)    {        return this.parseXml2Bean(xmlPath, null);    }    // 将配置文件映射为javaBean    public Object parseXml2Bean(String xmlPath, String rulePath)    {        String ruleXmlPath = "";        if (rulePath == null)        {            ruleXmlPath = "conf/rulefile/xmlrules.xml";// default数据装载逻辑配置文件        }        else        {            ruleXmlPath = rulePath;        }        String datafileName = "";        URL rulesURL = null;        String basePath = XmlParser.class.getResource("/").getPath();        datafileName = basePath + xmlPath;        rulesURL = XmlParser.class.getClassLoader().getResource(basePath + ruleXmlPath);        Digester d = DigesterLoader.createDigester(rulesURL); // url形式        d.setClassLoader(XmlParser.class.getClassLoader());        try        {            object = d.parse(XmlParser.class.getClassLoader().getResourceAsStream(datafileName)); // InputStream input        }        catch (IOException e)        {            throw new ParseException(104, e);        }        catch (SAXException e)        {            throw new ParseException(105, e);        }        return object;    }}
依赖apache的四个包:

commons-digester-2.1.jar

commons-logging-1.1.1.jar

commons-beanutils-1.8.3.jar

commons-collections-3.2.1.jar

 

用到类Digester、DigesterLoader等,引入commons-digester-2.1.jar

用到类Log、LogFactory等,引入commons-logging-1.1.1.jar

用到类DynaProperty等,引入commons-beanutils-1.8.3.jar

至于commons-collections-3.2.1.jar,在以下所示实例中,不引入也可以,还没有涉及到这个包,在以后的应用的,根据具体情况确定是否引入。


import java.io.IOException;import java.io.InputStream;import org.apache.commons.digester.Digester;import org.apache.commons.digester.xmlrules.DigesterLoader;import org.xml.sax.InputSource;import org.xml.sax.SAXException;import com.hs.vsm.secservice.impl.module.ips.policybean.PolicyExportImport;public class XmlParser{    public void parseByDigester(InputStream is) throws IOException, SAXException    {        Digester digester = DigesterLoader.createDigester(new InputSource(XmlParser.class                .getResourceAsStream("/conf/xmlfile/rulefile/xmlrules.xml"))); // InputSource(InputStream iS)        PolicyExportImport ipsPolicy = (PolicyExportImport) digester.parse(is); // InputStream input    }    public static void main(String[] args) throws IOException, SAXException    {        String file = "/conf/xmlfile/ipspolicy/ipspolicy.xml";        new XmlParser().parseByDigester(XmlParser.class.getResourceAsStream(file));    }}


原创粉丝点击