Parsing XML from website to an Android device

后端 未结 5 1628
猫巷女王i
猫巷女王i 2021-02-10 15:56

I am starting an Android application that will parse XML from the web. I\'ve created a few Android apps but they\'ve never involved parsing XML and I was wondering if anyone had

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-10 16:19

    Here's an example:

            try {
                URL url = new URL(/*your xml url*/);
                URLConnection conn = url.openConnection();
    
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(conn.getInputStream());
    
                NodeList nodes = doc.getElementsByTagName(/*tag from xml file*/);
                for (int i = 0; i < nodes.getLength(); i++) {
                    Element element = (Element) nodes.item(i);
                    NodeList title = element.getElementsByTagName(/*item within the tag*/);
                    Element line = (Element) title.item(0);
                    phoneNumberList.add(line.getTextContent());
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
    

    In my example, my XML file looks a little like:

    
       
          555-555-5555
       
       
          555-555-5555
       
    
    

    and I would replace /*tag from xml file*/ with "phone" and /*item within the tag*/ with "string".

提交回复
热议问题