Skip to content Skip to sidebar Skip to footer

How To Parse Xml File Using Dom Parsing?

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 public class MainActiv

Solution 1:

Try this:

publicclassDomParserSampleActivityextendsActivity {
    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ScrollViewmScrView1=newScrollView(this);

        /** Create a new layout to display the view */LinearLayoutlayout=newLinearLayout(this);
        layout.setOrientation(1);

        /** Create a new textview array to display the results */
        TextView id[];
        TextView published[];
        TextView content[];
        TextView title[];

        TextView mediacontent[];
        TextView mediathumbnail[];

        try {
            URLurl=newURL(
                    "http://gdata.youtube.com/feeds/api/users/estudiosabiertostv/uploads");
            DocumentBuilderFactorydbf= DocumentBuilderFactory.newInstance();
            DocumentBuilderdb= dbf.newDocumentBuilder();
            Documentdoc= db.parse(newInputSource(url.openStream()));
            doc.getDocumentElement().normalize();

            NodeListnodeList= doc.getElementsByTagName("entry");

            /** Assign textview array length by arraylist size */
            id = newTextView[nodeList.getLength()];
            published = newTextView[nodeList.getLength()];
            content = newTextView[nodeList.getLength()];
            title = newTextView[nodeList.getLength()];
            mediacontent = newTextView[nodeList.getLength()];
            mediathumbnail = newTextView[nodeList.getLength()];

            for (inti=0; i < nodeList.getLength(); i++) {

                Nodenode= nodeList.item(i);

                id[i] = newTextView(this);
                published[i] = newTextView(this);
                content[i] = newTextView(this);
                title[i] = newTextView(this);

                ElementfstElmnt= (Element) node;

                NodeListidList= fstElmnt.getElementsByTagName("id");
                ElementidElement= (Element) idList.item(0);
                idList = idElement.getChildNodes();
                id[i].setText("Id is = "
                        + ((Node) idList.item(0)).getNodeValue());

                Log.v("TAG","id: "+idList.item(0).getNodeValue());

                NodeListpublishedList= fstElmnt
                        .getElementsByTagName("published");
                ElementpublishedElement= (Element) publishedList.item(0);
                publishedList = publishedElement.getChildNodes();
                published[i].setText("published is = "
                        + ((Node) publishedList.item(0)).getNodeValue());

                Log.v("TAG","published: "+publishedList.item(0).getNodeValue());

                NodeListcontentList= fstElmnt.getElementsByTagName("content");
                ElementcontentElement= (Element) contentList.item(0);
                contentList = contentElement.getChildNodes();
                content[i].setText("content is = "
                        + ((Node) contentList.item(0)).getNodeValue());

                Log.v("TAG","content: "+contentList.item(0).getNodeValue());

                NodeListtitleList= fstElmnt.getElementsByTagName("title");
                ElementtitleElement= (Element) titleList.item(0);
                titleList = titleElement.getChildNodes();
                title[i].setText("title is = "
                        + ((Node) titleList.item(0)).getNodeValue());

                Log.v("TAG","titulo: "+titleList.item(0).getNodeValue());

                NodeListnodeList1= fstElmnt
                        .getElementsByTagName("media:group");

                for (intj=0; j < nodeList1.getLength(); j++) {
                    Nodenode1= nodeList1.item(j);
                    mediacontent[j] = newTextView(this);
                    mediathumbnail[j] = newTextView(this);

                    ElementsecondElmnt= (Element) node1;

                    NodeListmediacontentList= secondElmnt
                            .getElementsByTagName("media:content");
                    ElementmediacontentElement= (Element) mediacontentList
                            .item(0);
                    mediacontent[j].setText("mediacontent url is = "
                            + mediacontentElement.getAttribute("url"));

                    Log.v("TAG","MEDIACONTENT: "+mediacontentElement.getAttribute("url"));

                    NodeListmediathumbnailList= secondElmnt
                            .getElementsByTagName("media:thumbnail");
                    ElementmediathumbnailElement= (Element) mediathumbnailList
                            .item(0);
                    mediathumbnail[j].setText("mediathumbnail url is = "
                            + mediathumbnailElement.getAttribute("url"));

                    Log.v("TAG","MEDIATHUMBNAIL: "+mediathumbnailElement.getAttribute("url"));

                    layout.addView(mediacontent[j]);
                    layout.addView(mediathumbnail[j]);
                }

                layout.addView(id[i]);
                layout.addView(published[i]);
                layout.addView(content[i]);
                layout.addView(title[i]);

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

        /** Set the layout view to display */

        mScrView1.addView(layout);
        setContentView(mScrView1);
    }
}

Do not forget to do so within a thread or failing that, use these lines After the onCreate()

    StrictMode.ThreadPolicypolicy=newStrictMode.ThreadPolicy.Builder()
.permitAll().build();
    StrictMode.setThreadPolicy(policy);

Solution 2:

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;

publicclassXMLParser {

    public String getXmlFromUrl(String urll) {
        Stringresponse="";
        try {
            URLConnectionconn=null;
            InputStreaminputStream=null;
            URLurl=newURL(urll);
            conn = url.openConnection();
            conn.setConnectTimeout(10000);
            HttpURLConnectionhttpConn= (HttpURLConnection) conn;
            httpConn.setRequestMethod("GET");
            httpConn.setConnectTimeout(10000);
            httpConn.connect();
            if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = httpConn.getInputStream();
            }
            BufferedReaderin=newBufferedReader(newInputStreamReader(inputStream));
            StringWriter writer=newStringWriter();
            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) {
        Documentdoc=null;
        DocumentBuilderFactorydbf= DocumentBuilderFactory.newInstance();

        try {

            DocumentBuilderdb= dbf.newDocumentBuilder();

            InputSourceis=newInputSource();
            is.setCharacterStream(newStringReader(xml));
            doc = db.parse(is);

        } catch (ParserConfigurationException e) {
            Log.e("Error: ", e.getMessage());
            returnnull;
        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());
            returnnull;
        } catch (IOException e) {
            Log.e("Error: ", e.getMessage());
            returnnull;
        }
        // return DOMreturn doc;
    }

    public String getValue(Element item, String str) {
        NodeListn= item.getElementsByTagName(str);
        returnthis.getElementValue(n.item(0));
    }

    publicfinal 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

<results><result><title>title1</title><description>description1</description><lien>lien1</lien></result><result><title>title2</title><description>description2</description><lien>lien2</lien></result></results>

and, to use it in your Activity

finalStringKEY_ITEM="result"; // parent nodefinalStringKEY_TITLE="title";
finalStringKEY_DESC="description";
finalStringKEY_LINK="lien";


XMLParserparser=newXMLParser();
Stringxml= parser.getXmlFromUrl("YourXmlURL"); // getting XMLDocumentdoc= parser.getDomElement(xml); // getting DOM elementNodeListelements= doc.getElementsByTagName(KEY_ITEM);
List<String> title= newArrayList<String>(); // or other type
List<String> descp= newArrayList<String>();
Element e;

for (inti=0; i < elements.getLength(); i++) {
    e = (Element) elements.item(i);
    title.add(parser.getValue(e, KEY_TITLE));
    descp.add(parser.getValue(e,KEY_DESC));
}

Post a Comment for "How To Parse Xml File Using Dom Parsing?"