SAX 解析XML 将xml转换成javaBean

前端之家收集整理的这篇文章主要介绍了SAX 解析XML 将xml转换成javaBean前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

SAX没有提供,直接将xml转成自定义javaBean的方法。@H_301_1@

自己写了一个工具类通过反射机制转换。可以支持多数组。@H_301_1@

/**
 * Created by tiantao on 16-7-20.
 */
public class SaxUtil {

    private static final Logger logger = LoggerFactory.getLogger(SaxUtil.class);


    public static RequestBean converyRequestBean(String xml) {

        RequestBean requestBean = new RequestBean();
        try {
            SAXBuilder sb = new SAXBuilder();
            StringReader read = new StringReader(xml);
            InputSource source = new InputSource(read);
            Document doc = sb.build(source);
            Element root = doc.getRootElement();

            recursionConvery(root,RequestBean.class,requestBean);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
        return requestBean;
    }

    private static void recursionConvery(Element e,Class<?> clazz,Object o) throws IllegalAccessException,InstantiationException,InvocationTargetException,NoSuchMethodException {
        List<Element> el = e.getChildren();
        if (el.size() > 0) {
            for (Element element : el) {
                String childClassName = element.getName();
                String getMethodName = "get" + childClassName.substring(0,1).toUpperCase() + childClassName.substring(1);
                String setMethodName = "set" + childClassName.substring(0,1).toUpperCase() + childClassName.substring(1);

                //当属性名为Class或class时,特殊处理get方法写成getclass
                if ("getClass".equals(getMethodName)) {
                    getMethodName = "getclass";
                }

                Class<?> clazz1 = null;
                Method[] ms = clazz.getMethods();
                for (Method m : ms) {
                    if (getMethodName.equals(m.getName())) {
                        clazz1 = m.getReturnType();
                        if (clazz1.isArray()) {
                            int arraySize = 0;
                            for (Element element1 : el) {
                                if (element1.getName().equals(clazz1.getComponentType().getSimpleName())){
                                    arraySize ++;
                                }
                            }
                            Object arrayObjects = Array.newInstance(clazz1.getComponentType(),arraySize);
                            int n = 0;
                            for (Element element1 : el) {
                                if (element1.getName().equals(clazz1.getComponentType().getSimpleName())){
                                    Object oneO = clazz1.getComponentType().newInstance();
                                    recursionConvery(element1,clazz1.getComponentType(),oneO);
                                    Array.set(arrayObjects,n,oneO);
                                    n ++;
                                }
                            }
                            Method setMethod = clazz.getMethod(setMethodName,clazz1);
                            setMethod.invoke(o,arrayObjects);
                        } else {
                            if (element.getChildren() != null && element.getChildren().size() > 0) {
                                Object o1 = clazz1.newInstance();
                                recursionConvery(element,clazz1,o1);
                                Method setMethod = clazz.getMethod(setMethodName,clazz1);
                                setMethod.invoke(o,o1);
                            } else {
                                Method setMethod = clazz.getMethod(setMethodName,clazz1);
                                setValue(element,setMethod,o);
                            }
                        }
                    }
                }
            }
        }
    }


    private static void setValue(Element element,Method method,Object o) throws InvocationTargetException,IllegalAccessException {
        Class<?>[] c = method.getParameterTypes();
        String text = element.getTextTrim();
        Object v = null;
        String cn = c[0].getSimpleName();

        if ("int".equals(cn) || "Integer".equals(cn)) {
            v = Integer.parseInt(text);
        } else if ("long".equals(cn) || "Long".equals(cn)) {
            v = Long.parseLong(text);
        } else if ("double".equals(cn) || "Double".equals(cn)) {
            v = Double.parseDouble(text);
        } else if ("float".equals(cn) || "Float".equals(cn)) {
            v = Float.parseFloat(text);
        } else {
            v = text;
        }

        method.invoke(o,v);

    }

    public static void main(String[] args) {

        for (int i = 0; i < 1; i++) {
            new Thread(new Thread() {
                @Override
                public void run() {
                    //String xml = "<?xml version='1.0' encoding='UTF-8' ?><Request><HuaWeiPluginStatus>301</HuaWeiPluginStatus><FencePolicyId>sss</FencePolicyId><OperID><TenantID>mdm</TenantID><ClientUID>1b81d8c648155ab178ba11f18382dd836939267e</ClientUID><FlowNum>1413937173</FlowNum><Timezone>-1</Timezone><Result>-1</Result><ClientVersion>4.0.1.0</ClientVersion></OperID><AppInfo><ClientOS>1</ClientOS><Class>0</Class><OSVersion>5.0.2</OSVersion><CateId>0</CateId><StartIdx>0</StartIdx><RowNum>13</RowNum></AppInfo><DeviceUpdate><Battery><BatteryLevel>1</BatteryLevel></Battery></DeviceUpdate></Request>";
                    //String xml = "<?xml version='1.0' encoding='UTF-8' ?><Request><OperID><TenantID>mdm</TenantID><ClientUID>1b81d8c648155ab178ba11f18382dd836939267e</ClientUID><FlowNum>dfdbf394-2ea7-4fb2-b7b9-8bfabb7de516</FlowNum><Timezone>-1</Timezone><Result>-1</Result><ClientVersion>4.0.1.0</ClientVersion></OperID><AppList TotalCount=\"1\"><App><PackageName>com.nq.mdm</PackageName><Name>NQSky</Name><VersionName>4.0.1.0</VersionName><VersionCode>400100019</VersionCode><Size>15171584</Size><Status>1</Status><IsInputKnox>0</IsInputKnox></App></AppList></Request>";
                    for (int i = 0; i < 1; i++) {
                        long start = System.currentTimeMillis();
                        RequestBean requestBean = SaxUtil.converyRequestBean(xml);
                        System.out.println(requestBean.toString());
                        //RequestBean requestBean = (RequestBean) JaxbUtil.fromXML(xml,RequestBean.class);
                        System.out.println(System.currentTimeMillis() - start);
                    }
                    super.run();
                }
            }).start();
        }
    }
}
代码需要一些其他类,不能直接运行。迭代方法和设置属性值都是可以用的。

猜你在找的XML相关文章