Android远程XML解析(文档构建器)

时间:2012-10-06 17:14:36

标签: java android xml parsing dom

我一直在网上聊天几天,我真的需要一些帮助,我试图将一个XML文档从Web服务器解析为android中的ListView,我已经研究了如何使用本地文件和这很好,但无论我发现无论是在堆栈或其他网站上,它似乎都没有工作,任何人都可以帮助我吗?我知道页面存在且有效......我现在把所有的头发拉出来,请求帮助:)

下面是我的方法代码,这是在创建后调用的,在项目的onclicklistener之后调用,我也在使用文档构建器工厂方法。

private void xmlparse()
{

    try {

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dbf.newDocumentBuilder();
            Document doc = builder.parse(new URL("URL in here").openConnection().getInputStream());

            doc.getDocumentElement().normalize();

            NodeList nList = doc.getElementsByTagName("item");

            for (int temp = 0; temp < nList.getLength(); temp++) {

               Node nNode = nList.item(temp);
               if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                  Element eElement = (Element) nNode;

                  titles.add(getTagValue(TITLE_1, eElement));  //TITLE_1 is the xml tag title

               }
            }


          } catch (Exception e) {
            e.printStackTrace();
          }
}

private String getTagValue(String sTag, Element eElement) {
        NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();

            Node nValue = (Node) nlList.item(0);

        return nValue.getNodeValue();
     }

我是否遗漏了一些愚蠢的东西或者我完全错过了球?任何人都可以指向我的信息,这将有助于或只是让我知道:)

干杯!!

1 个答案:

答案 0 :(得分:1)

我已经做了哪个任务,你应该这样做:

                //Formattage des strings pour le passage en URL
                from = URLEncoder.encode(from, "UTF-8");
                to = URLEncoder.encode(to, "UTF-8");
                String addressToConnect = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins="+from+"&destinations="+to+"&mode=driving&units="+unit+"&sensor=false";

                //Partie connexion
                URL url = new URL(addressToConnect);
                HttpURLConnection connexion = (HttpURLConnection) url.openConnection();
                connexion.connect();
                InputSource geocoderResultInputSource;
                geocoderResultInputSource = new InputSource(connexion.getInputStream());

                //Partie XML/XPATH

                Document geocoderResultDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(geocoderResultInputSource);
                XPath xpath = XPathFactory.newInstance().newXPath();

                //On s'assure que la requete envoy�e � l'API � bien renvoy�e un STATUS = OK cf. Google API
                NodeList nodeListCodeResult = (NodeList) xpath.evaluate("//status", geocoderResultDocument, XPathConstants.NODESET);
等等......

希望它有所帮助,