如何使用Dom解析来解析XML文件



我的问题是我正在使用Dom解析来解析下面的xml文件,但这给了我NullPointerException的错误。

如有任何帮助,我们将不胜感激。

主要活动.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);
    }
}

尝试这个

创建一个新的类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 "";
    }
}

例如

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

以及,在活动中使用

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));
}

相关内容

  • 没有找到相关文章

最新更新