Java解析Xml格式的响应信息

1.请求/响应代码

public List<ZxAjxxListItem> getZxAjxxList() {
        
        List<ZxAjxxListItem> r = null;
        if (login()) {
            HttpGet get = null;
            try {          // 请求资源地址
                String url=clientAccountAndPassword.getAjcxGridUrl();
                get = new HttpGet(url);          // 响应信息
                HttpResponse response = httpClient.execute(get);
                if (response.getStatusLine().getStatusCode() == 200) {            // 响应资源内容
                    String responseXml = EntityUtils.toString(response.getEntity(), "UTF-8");
                    r = getXmltoZxAjxxListItem(responseXml);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            } finally {
                if (get != null) {
                    get.abort();
                }
            }
        }
        
        return r;
    }

2.解析响应xml格式信息代码

private List<ZxAjxxListItem> getXmltoZxAjxxListItem(String xmlString) {
        if(StringUtils.isBlank(xmlString)) return null;
        Document doc = null;
        List<ZxAjxxListItem> zxAjxxListItem = null;
        try {
            // 将字符串转为XML
            doc = DocumentHelper.parseText(xmlString);
            // 获取根节点
            Element rootElt = doc.getRootElement();
            // 获取row节点
            zxAjxxListItem = new ArrayList<ZxAjxxListItem>();
            Iterator rowList = rootElt.elementIterator("row");
            ZxAjxxListItem bean = null;
            while (rowList.hasNext()) {
                bean = new ZxAjxxListItem();
                Element row = (Element) rowList.next();
                bean .setAhdm(row.attributeValue("id"));
                // 获取cell节点
                Iterator cellList = row.elementIterator("cell");
                List<String> strlist = new ArrayList<String>();
                while (cellList.hasNext()) {
                    Element cell = (Element) cellList.next();
                    strlist.add(cell.getText());
                }
                bean.setAjzt(strlist.get(2));
                bean.setXlabh(strlist.get(3));
                bean.setAh(strlist.get(4));
                bean.setDsr(strlist.get(5));
                bean.setAy(strlist.get(6));
                zxAjxxListItem.add(bean);
            }
            return zxAjxxListItem;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return zxAjxxListItem;
    }

相关推荐