Chinaunix首页 | 论坛 | 博客
  • 博客访问: 556981
  • 博文数量: 48
  • 博客积分: 4026
  • 博客等级: 上校
  • 技术积分: 622
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-26 13:59
文章分类

全部博文(48)

文章存档

2011年(3)

2010年(6)

2009年(12)

2008年(27)

我的朋友

分类:

2008-09-12 11:59:43

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 HashMap<String, ArrayList> treeWalk(Element element,
            HashMap<String, 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())) {
                        ArrayList<String> temp = new ArrayList<String>();
                        temp.add(node.getText().trim());
                        map.put(node.getName(), temp);
                    } else {

                        ArrayList<String> 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(List<Node> nodes) {
        HashMap<String, ArrayList> map = new HashMap<String, 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,
            HashMap<String, 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[i].getName();
            String tempMethod = "set" + tempField.substring(0, 1).toUpperCase()
                    + tempField.substring(1);// 根据字段名拼凑其set方法名

            ArrayList<String> 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[i].getType().isArray()) {    //如果这个属性是String[]类型

                Class<?> clazz = fields[i].getType();
                cls = new Class[] { clazz };
                obj = new Object[] { clazz.cast(xmlValue.split(",")) };
            } else {                   //如果这个属性是其他基本数据类型

    Class<?> clazz = fields[i].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;
    }
}

阅读(2165) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~