How to Parse XML file Using Dom Parsing?

后端 未结 2 1062
甜味超标
甜味超标 2021-01-29 11:18

My Problem is I am Using Dom Parsing to parse below xml file but this give me error of NullPointerException.

Any Help Would be Appreciated.

MainActivity.java

2条回答
  •  我在风中等你
    2021-01-29 12:03

    try this

    create a new class XMLParser

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.StringReader;
    import java.io.StringWriter;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLConnection;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    
    import android.util.Log;
    
    public class XMLParser {
    
        public String getXmlFromUrl(String urll) {
            String response = "";
            try {
                URLConnection conn = null;
                InputStream inputStream = null;
                URL url = new URL(urll);
                conn = url.openConnection();
                conn.setConnectTimeout(10000);
                HttpURLConnection httpConn = (HttpURLConnection) conn;
                httpConn.setRequestMethod("GET");
                httpConn.setConnectTimeout(10000);
                httpConn.connect();
                if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    inputStream = httpConn.getInputStream();
                }
                BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                StringWriter writer=new StringWriter();
                String line="";
                while ( null!=(line=in.readLine())){
                    writer.write(line); 
                }
                response =writer.toString(); 
                }
            catch (Exception e) {
                // TODO: handle exception
            }
            return response;
        }
    
        public Document getDomElement(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) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }
            // return DOM
            return doc;
        }
    
        public String getValue(Element item, String str) {
            NodeList n = item.getElementsByTagName(str);
            return this.getElementValue(n.item(0));
        }
    
        public final String getElementValue(Node elem) {
            Node child;
            if (elem != null) {
                if (elem.hasChildNodes()) {
                    for (child = elem.getFirstChild(); child != null; child = child
                            .getNextSibling()) {
                        if (child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE) {
                            return child.getNodeValue();
                        }
                    }
                }
            }
            return "";
        }
    }
    

    your xml for example

    
       
         title1
         description1
         lien1
       
       
         title2
         description2
         lien2
       
    
    

    and, to use it in your Activity

    final String KEY_ITEM = "result"; // parent node
    final String KEY_TITLE = "title";
    final String KEY_DESC = "description";
    final String KEY_LINK = "lien";
    
    
    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl("YourXmlURL"); // getting XML
    Document doc = parser.getDomElement(xml); // getting DOM element
    
    NodeList elements = doc.getElementsByTagName(KEY_ITEM);
    List title= new ArrayList(); // or other type
    List descp= new ArrayList();
    Element e;
    
    for (int i = 0; i < elements.getLength(); i++) {
        e = (Element) elements.item(i);
        title.add(parser.getValue(e, KEY_TITLE));
        descp.add(parser.getValue(e,KEY_DESC));
    }
    

提交回复
热议问题