2012-08-24 127 views
-1

我的问题是我使用Dom解析来解析XML文件,但这给我错误的NullPointerException。如何使用Dom解析来解析XML文件?

任何帮助将被赞赏。

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

安置自己的logcat的后这样做错误。 – Guykun

+0

@Downvoter为什么downvoting,请给我downvote的理由? –

+0

@Guykun Cursor进入catch块,logcat中只显示“java.lang.nullpointerexception”。 –

回答

3

试试这个:

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

不要忘了在一个线程中或做不到这一点,使用这些线 的的onCreate()

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() 
.permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 
1

试试这个

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

你的XML例如

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

,并在使用它你活性状况TY

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

但是如何使用你的代码解析我的xml文件的? –

+0

在您的活动中使用e.getAttribute(“yourAttribute”),或将其添加到XMLParser类的getValue()中 –