从响应这是在XML中读取数据 [英] Reading data from response which is in xml

查看:93
本文介绍了从响应这是在XML中读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发的应用程序,在我看过的数据,我会从的 respose 的xml格式得到。那么,怎样才能实现它。

I am developing an application, in that I have read data which I will get from respose in xml format. So how can implement it.

我不发展在我的身边的web应用程序。但是,检索一个URL,我会得到一个XML数据作为响应。

I am not developing web app in my side. But retrieving an url and I will get an xml data as response.

推荐答案

创建一个类XMLfunctions

Create a class XMLfunctions

public class XMLfunctions {

public final static Document XMLfromString(String xml){

    Document doc = null;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        doc = db.parse(is); 

    } catch (ParserConfigurationException e) {
        System.out.println("XML parse error: " + e.getMessage());
        return null;
    } catch (SAXException e) {
        System.out.println("Wrong XML file structure: " + e.getMessage());
        return null;
    } catch (IOException e) {
        System.out.println("I/O exeption: " + e.getMessage());
        return null;
    }

    return doc;

}


/** Returns element value
  * @param elem element (it is XML tag)
  * @return Element value otherwise empty String
  */
 public final static String getElementValue( Node elem ) {
     Node kid;
     if( elem != null){
         if (elem.hasChildNodes()){
             for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                 if( kid.getNodeType() == Node.TEXT_NODE  ){
                     return kid.getNodeValue();
                 }
             }
         }
     }
     return "";
 }

    public static String getTopNewsXML(){    
        String line = null;

        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("url");

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            line = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        } catch (MalformedURLException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        } catch (IOException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        }
        String st= ParseXMLNode(line,"doc");
        return st;

    }

public static String ParseXMLNode(String str,String node){
     String xmlRecords = str;
     String results = "";
     String[] result = new String [10];
     StringBuffer sb = new StringBuffer();
     try {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         InputSource is = new InputSource();
         is.setCharacterStream(new StringReader(xmlRecords));
         Document doc = db.parse(is);
         NodeList nlist = doc.getElementsByTagName(node);

         sb.append("<results count=");
         sb.append("\"10\"");
         sb.append(">\r\n");


         for (int i = 0; i < nlist.getLength(); i++) {
                Node node1 = nlist.item(i);
                if (node1.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node1;
                    NodeList nodelist = element.getElementsByTagName("str");
                    Element element1 = (Element) nodelist.item(0);
                    NodeList title = element1.getChildNodes();

                    System.out.print((title.item(0)).getNodeValue());
                    sb.append("<result>\r\n");
                        sb.append("<title>");
                            sb.append(title.item(0).getNodeValue().trim());
                        sb.append("</title>\r\n");

                    sb.append("</result>\r\n");
                    result[i] = title.item(0).getNodeValue();

                   }
            }
         sb.append("</results>");
     } catch (Exception e) {
         System.out.println("Exception........"+results );
         e.printStackTrace();
     }
     return sb.toString();
     }
}

public static int numResults(Document doc) {
    Node results = doc.getDocumentElement();
    int res = -1;
    try {
        res = Integer.valueOf(results.getAttributes().getNamedItem("count")
                .getNodeValue());
    } catch (Exception e) {
        res = -1;
    }
    return res;
}

public static String getValue(Element item, String str) {
    NodeList n = item.getElementsByTagName(str);
    return XMLfunctions.getElementValue(n.item(0));
}

在您的活动

ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

        String xml = XMLfunctions.getTopNewsXML();
        Document doc = XMLfunctions.XMLfromString(xml);

        int numResults = XMLfunctions.numResults(doc);
        Log.d(LOG_TAG, "Number of Results: " + numResults);
        if ((numResults <= 0)) {
            Toast.makeText(ParentActivity.this, "No Result Found",Toast.LENGTH_LONG).show();
            return null;
        }

        NodeList nodes = doc.getElementsByTagName("result");

        for (int i = 0; i < nodes.getLength(); i++) {
            HashMap<String, String> map = new HashMap<String, String>();

            Element e = (Element) nodes.item(i);
            map.put("title", XMLfunctions.getValue(e, "title"));
            mylist.add(map);
        }
        return mylist;

然后就可以把数据列表

Then you can put the data in the list

这篇关于从响应这是在XML中读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆