免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2293 | 回复: 0
打印 上一主题 下一主题

通用的解析xml文件并封装成FormBean的方法 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-09-12 11:59 |只看该作者 |倒序浏览

public class PraseXmlUtil {
    @SuppressWarnings("unchecked")
    public static Object praseXml(String xPath,String xml,Object form)
            throws Exception, DocumentException {
        List selectNodes = getRootElement(read(xml)).selectNodes(xPath);
        return getFormBean(form, treeWalk(selectNodes));
        
    }
    /**
     * ################################################################################### #
     * 返回该文档的根元素 # #
     *
     * @param doc #
     * @return #
     * ###################################################################################
     */
    public static final Element getRootElement(Document doc) {
        return doc.getRootElement();
    }
    /**
     * ################################################################################### #
     * 返回单结点下的值
     *
     * @param String #
     * @return #
     * ###################################################################################
     * @throws DocumentException
     * @throws MalformedURLException
     */
    public static final String getSingleElementValue(String xPath,String xml) throws DocumentException {
        return getRootElement(read(xml)).selectSingleNode(xPath).getText();
    }
    /**
     * ################################################################################### #
     * Xml 转 String # #
     *
     * @param document #
     * @return #
     * ###################################################################################
     */
    @SuppressWarnings("unused")
    private String getString(Document document) {
        return document.asXML();
    }
    /**
     * ################################################################################### #
     * 读入一个xml格式字符串,返回这个Document # #
     *
     * @param fileName #
     * @return #
     * @throws MalformedURLException #
     * @throws DocumentException #
     * ###################################################################################
     */
    public static final Document read(String xml)throws DocumentException {
        Document document = DocumentHelper.parseText(xml);
        return document;
    }
    /**
     * ################################################################################### #
     * 遍历传入元素下面所有节点 # #
     *
     * @param element #
     * ###################################################################################
     */
    @SuppressWarnings("unchecked")
    private static HashMapString, ArrayList> treeWalk(Element element,
            HashMapString, ArrayList> map) {
        for (int i = 0, size = element.nodeCount(); i  size; i++) {
            Node node = element.node(i);
            if (node instanceof Element) {
               
                    if (!map.containsKey(node.getName())) {
                        ArrayListString> temp = new ArrayListString>();
                        temp.add(node.getText().trim());
                        map.put(node.getName(), temp);
                    } else {
                        ArrayListString> temp = map.get(node.getName());
                        temp.add(node.getText().trim());
                        map.put(node.getName(), temp);
                    }
                treeWalk((Element) node, map);
            }
        }
        return map;
    }
    /**
     *
     * ################################################################################### #
     * 遍历所有节点 # #
     *
     * @param fileName #
     * @throws Exception #
     * ###################################################################################
     */
    public static HashMap treeWalk(ListNode> nodes) {
        HashMapString, ArrayList> map = new HashMapString, ArrayList>();
        for (int i = 0; i  nodes.size(); i++) {
            Element element = (Element) nodes.get(i);
            treeWalk(element, map);
        }
        return map;
    }
    /**
     * 利用反射得到该xml所对应的formbean的对象
     *
     * @param obj
     * @param fieldName
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     * @throws InstantiationException
     */
    @SuppressWarnings("unchecked")
    private static Object getFormBean(Object form,
            HashMapString, ArrayList> map) throws SecurityException,
            IllegalArgumentException, IllegalAccessException,
            InvocationTargetException, NoSuchMethodException,
            InstantiationException {
        Class?> classType = form.getClass();
        Field[] fields = classType.getDeclaredFields();// 得到此类所有的字段
        Method method = null;
        for (int i = 0; i  fields.length; i++) {
            String tempField = fields.getName();
            String tempMethod = "set" + tempField.substring(0, 1).toUpperCase()
                    + tempField.substring(1);// 根据字段名拼凑其set方法名
            ArrayListString> temp = map.get(tempField);
            if (temp == null) {
                continue;
            }
String xmlValue = temp.toString().substring(1,temp.toString().length() - 1);
            Class cls[] = new Class[1];
            Object obj[] = new Object[1];
            // 得到每个字段的数据类型,也即是set方法的参数类型
     if (fields.getType().isArray()) {    //如果这个属性是String[]类型
                Class?> clazz = fields.getType();
                cls = new Class[] { clazz };
                obj = new Object[] { clazz.cast(xmlValue.split(",")) };
            } else {                   //如果这个属性是其他基本数据类型
    Class?> clazz = fields.getType();
    Constructor?> constructor = clazz.getConstructor(new Class[] { String.class });
                cls = new Class[] { clazz };
                obj = new Object[] { constructor.newInstance(xmlValue) };
            }
            method = classType.getMethod(tempMethod, cls);
            method.invoke(form, obj);
        }
        return form;
    }
}

下面是运行的demo

文件:
AutoPraseXml.rar
大小:
499KB
下载:
下载


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/57965/showart_1188751.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP