xml解析工具类

2 篇文章 0 订阅
1 篇文章 0 订阅

参照:http://blog.csdn.net/nugongahou110/article/details/46963767点击打开链接


1:自定义javaBean:


public class TerminalInit_Bean extends Base_Bean{

    private String updateStatus; 
    private String updateAddress; 
    private String msgExt; 
    private String downParam; 
    private String respCode; 
    private String respDesc; 
    public String getRespCode() {
        return respCode;
    }

    public void setRespCode(String respCode) {
        this.respCode = respCode;
    }

    public String getRespDesc() {
        return respDesc;
    }

    public void setRespDesc(String respDesc) {
        this.respDesc = respDesc;
    }

    public String getUpdateStatus() {
        return updateStatus;
    }

    public void setUpdateStatus(String updateStatus) {
        this.updateStatus = updateStatus;
    }

    public String getUpdateAddress() {
        return updateAddress;
    }

    public void setUpdateAddress(String updateAddress) {
        this.updateAddress = updateAddress;
    }

    public String getMsgExt() {
        return msgExt;
    }

    public void setMsgExt(String msgExt) {
        this.msgExt = msgExt;
    }

    public String getDownParam() {
        return downParam;
    }

    public void setDownParam(String downParam) {
        this.downParam = downParam;
    }
}

2:使用方法

Object obj = null;
try {
    obj = XmlUtils.getBeanListByParseXml(new ByteArrayInputStream(Info.netResult.getBytes()),
            "upPay", cla);
} catch (Exception e) {
    Info.cuowu = "xml报文解析失败";
    listener.onFail();
}

3:工具类

public class XmlUtils {

    /**
     * 解析xml文件结构的方法, 返回一个对象
     *
     * @param inputStream 解析内容
     * @param beanRoot    外层Bean需要实例化对象的一个标识
     * @param beanClazz   Bean.class
     * @return 返回  object 对象
     * @throws Exception
     */
    public static <T, T1> Object getBeanListByParseXml(InputStream inputStream, String beanRoot, Class<T1> beanClazz)
            throws Exception {

        XmlPullParser parser = Xml.newPullParser();

        //最后结果
        Object result = null;
        //list  存放一堆item
        ArrayList<T> list = null;
        //内层ListBean
        T t = null;
        //外层Bean
        T1 bean = null;
        //一个计数器
        int count = 0;

        Field mField = null; //List

        Field mFieldList = null;

        String listName = "";

        try {
            parser.setInput(inputStream, "UTF-8");
            //获得当前标签类型
            int eventType = parser.getEventType();
            //如果不是xml文件结束标签,则一个一个向下解析
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                    //如果是xml文件开始标签,则初始化一些数据
                    case XmlPullParser.START_DOCUMENT:
                        //最后的结果
                        result = new Object();
                        //list
                        list = new ArrayList<T>();
                        break;
                    //开始标签
                    case XmlPullParser.START_TAG:
                        //获得标签的名字
                        String tagName = parser.getName();
                        //如果内层的ListBean已经实例化出来的话
                        if (t != null) {
                            try {
                                Field field = t.getClass().getDeclaredField(tagName);

                                if (!listName.equals(tagName)) {
                                    //判断当前标签在没在ListBean的属性中
                                    if (!tagName.equals(listName)) {
                                        //如果ListBean中有当前标签
                                        if (field != null) {
                                            //计数器+1
                                            count++;
                                            //将取出来的值赋给ListBean中对应的属性
                                            field.setAccessible(true);
                                            field.set(t, parser.nextText());
                                        }
                                    }
                                }

                            } catch (Exception e) {
                                //如果ListBean中没有当前标签,则会直接跳到这里,什么都不执行,然后再继续往下走
                            }
                            //如果外层的Bean已经实例化出来的话
                        } else if (bean != null) {
                            try {
                                //判断当前标签在没在Bean的属性中
                                Field field = beanClazz.getDeclaredField(tagName);
                                if (field.getType().getSimpleName().equals("List")) {

                                } else {
                                    //如果Bean中有当前标签
                                    if (field != null) {
                                        //计数器+1
                                        count++;
                                        //将取出来的值赋给Bean中对应的属性
                                        field.setAccessible(true);
                                        field.set(bean, parser.nextText());
                                    }
                                }
                            } catch (Exception e) {
                                //如果Bean中没有当前标签,则会直接跳到这里,什么都不执行,然后再继续往下走
                            }
                        }

                        try {
                            //判断当前标签类型是否为List
                            mField = beanClazz.getDeclaredField(tagName);
                            mField.setAccessible(true);
                            if (mField.getType().getSimpleName().equals("List")) { //判断标签是否为 一个 List 集合
                                Utils.log("listName = " + listName);
                                Utils.log("tagName = " + tagName);
                                if (!tagName.equals(listName)) { //判断是否为相同集合
                                    try {
                                        //如果不是相同一个集合,设置List                                        mFieldList.set(bean, list);
                                        //清空List
                                        list.clear();
                                    } catch (Exception e) {
                                        //防止设置List 空指针异常
                                    }
                                }
                                mFieldList = mField;
                                listName = tagName;
                                //实例化List集合中 对象类型
                                Class cla = (Class) (((ParameterizedType) mField.getGenericType())
                                        .getActualTypeArguments()[0]);
                                t = (T) cla.newInstance();
                            }
                        } catch (Exception e) {
                        }

                        //如果当前标签为我们传入的内层根标签,说明Bean需要实例化出来了
                        if (tagName.equals(beanRoot)) {
                            //Bean实例化出来
                            bean = beanClazz.newInstance();
                        }
                        break;
                    //结束标签
                    case XmlPullParser.END_TAG:
                        //如果当前标签为</item>
                        if (listName.equalsIgnoreCase(parser.getName())) {
                            //如果ListBean不为空
                            if (t != null) {
                                //保存到list中,同时也保存到了result中,因为list已经是保存在result中了,
                                //只不过刚才没有值,现在有值了
                                list.add(t);
                                //并且把ListBean置空,因为后续还有好多个item
                                t = null;
                            }
                        } else if (beanRoot.equalsIgnoreCase(parser.getName())) { //最后结束标签
                            try {
                                //设置 list   防止空指针异常
                                mFieldList.set(bean, list);
                            } catch (Exception e) {

                            }
                            //Bean保存到result                            result = bean;
                        }
                        break;
                }
                //移动到下一个标签
                eventType = parser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //如果计数器为0说明没有解析到任何数据
        if (count == 0) {
            //result置空就可以了
            result = null;
        }
        //result返回
        return result;
    }
}


  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * 本类是专门解析XML文件的,主要用于为系统读取自己的配置文件时提供最方便的解析操作 * @author HX * */ public class XmlManager { /** * 得到某节点下某个属性的值 * @param element 要获取属性的节点 * @param attributeName 要取值的属性名称 * @return 要获取的属性的值 * @author HX_2010-01-12 */ public static String getAttribute( Element element, String attributeName ) { return element.getAttribute( attributeName ); } /** * 获取指定节点下的文本 * @param element 要获取文本的节点 * @return 指定节点下的文本 * @author HX_2010-01-12 */ public static String getText( Element element ) { return element.getFirstChild().getNodeValue(); } /** * 解析某个xml文件,并在内存中创建DOM树 * @param xmlFile 要解析XML文件 * @return 解析某个配置文件后的Document * @throws Exception xml文件不存在 */ public static Document parse( String xmlFile ) throws Exception { // 绑定XML文件,建造DOM树 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document domTree = db.parse( xmlFile ); return domTree; } /** * 获得某节点下的某个子节点(指定子节点名称,和某个属性的值) * 即获取parentElement下名字叫childName,并且属性attributeName的值为attributeValue的子结点 * @param parentElement 要获取子节点的那个父节点 * @param childName 要获取的子节点名称 * @param attributeName 要指定的属性名称 * @param attributeValue 要指定的属性的值 * @return 符合条件的子节点 * @throws Exception 子结点不存在或有多个符合条件的子节点 * @author HX_2008-12-01 */ public static Element getChildElement( Element parentElement, String childName, String attributeName, String attributeValue ) throws Exception { NodeList list = parentElement.getElementsByTagName( childName ); int count = 0; Element curElement = null; for ( int i = 0 ; i < list.getLength() ; i ++ ) { Element child = ( Element )list.item( i ); String value = child.getAttribute( attributeName ); if ( true == value.equals( attributeValue ) ) { curElement =

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值