How to Parse XML file Using Dom Parsing?

≡放荡痞女 提交于 2019-12-20 07:47:44

问题


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 MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ScrollView mScrView1 = new ScrollView(this);

        /** Create a new layout to display the view */
        LinearLayout layout = new LinearLayout(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 {

            URL url = new URL(
                    "http://gdata.youtube.com/feeds/api/users/estudiosabiertostv/uploads");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize();

            NodeList nodeList = doc.getElementsByTagName("entry");

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

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

                Node node = nodeList.item(i);

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

                Element fstElmnt = (Element) node;

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

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

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

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

                NodeList nodeList1 = fstElmnt.getElementsByTagName("media:group");
                System.out.println("Size is:- " +nodeList1.getLength());

                for (int j = 0; j < nodeList1.getLength(); j++) {
                    Node node1 = nodeList1.item(j);
                    mediacontent[j] = new TextView(this);
                    mediathumbnail[j] = new TextView(this);
                    Element secondElmnt = (Element) node1;
                    NodeList mediacontentList = secondElmnt.getElementsByTagName("media:content");
                    Element mediacontentElement = (Element) mediacontentList.item(0);
                    mediacontentList = mediacontentElement.getChildNodes();
                    mediacontent[j].setText("mediacontent is = "
                            + ((Node) mediacontentList.item(0)).getNodeValue());
                    layout.addView(mediacontent[j]);
                }

                layout.addView(id[i]);
                layout.addView(published[i]);
                layout.addView(content[i]);
                layout.addView(title[i]);
            }
        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }

        /** Set the layout view to display */

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

回答1:


Try this:

public class DomParserSampleActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ScrollView mScrView1 = new ScrollView(this);

        /** Create a new layout to display the view */
        LinearLayout layout = new LinearLayout(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 {
            URL url = new URL(
                    "http://gdata.youtube.com/feeds/api/users/estudiosabiertostv/uploads");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize();

            NodeList nodeList = doc.getElementsByTagName("entry");

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

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

                Node node = nodeList.item(i);

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

                Element fstElmnt = (Element) node;

                NodeList idList = fstElmnt.getElementsByTagName("id");
                Element idElement = (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());

                NodeList publishedList = fstElmnt
                        .getElementsByTagName("published");
                Element publishedElement = (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());

                NodeList contentList = fstElmnt.getElementsByTagName("content");
                Element contentElement = (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());

                NodeList titleList = fstElmnt.getElementsByTagName("title");
                Element titleElement = (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());

                NodeList nodeList1 = fstElmnt
                        .getElementsByTagName("media:group");

                for (int j = 0; j < nodeList1.getLength(); j++) {
                    Node node1 = nodeList1.item(j);
                    mediacontent[j] = new TextView(this);
                    mediathumbnail[j] = new TextView(this);

                    Element secondElmnt = (Element) node1;

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

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

                    NodeList mediathumbnailList = secondElmnt
                            .getElementsByTagName("media:thumbnail");
                    Element mediathumbnailElement = (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.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
    StrictMode.setThreadPolicy(policy);



回答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;

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

<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

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<String> title= new ArrayList<String>(); // or other type
List<String> descp= new ArrayList<String>();
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));
}


来源:https://stackoverflow.com/questions/12106287/how-to-parse-xml-file-using-dom-parsing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!