我需要解析这个xml文件并需要在列表视图中显示但是我在运行此代码时遇到了问题。 任何人请帮我解决这个问题 提前谢谢
这是来自源http://purl.org/dc/elements/1.1/“version =”2.0“
的XML文件<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
<channel>
<title>MobileNations</title>
<description>
Mobile Nations brings to you the very best of Android Central, CrackBerry.com, PreCentral.net, TiPb.com, and WPCentral
</description>
<link>http://www.mobilenations.com/</link>
<language>en-us</language>
<lastBuildDate>Wed, 07 Aug 2013 06:15:01 -0400</lastBuildDate>
<pubDate>Wed, 07 Aug 2013 06:15:01 -0400</pubDate>
<item>
<title>
AT&T activates new 4G LTE markets, expands coverage in others
</title>
<description>
<p class="rtecenter"><img alt="AT&T" class="lightbox2 imagecache-w680h550 aligncenter" src="http://cdn.androidcentral.com/sites/androidcentral.com/files/imagecache/w680h550/postimages/108579/att-store-2.jpg" /></p> <h3> Six new markets, expanded coverage in Washington, D.C. and San Francisco areas</h3> <p><a href="http://www.androidcentral.com/tags/att" title="AT&T">AT&T</a> sends word that it's switched on 4G LTE service in six new markets, while expanding coverage in two major cities.</p> <p>From today, AT&T LTE should be available in —</p> <p><a href="http://www.androidcentral.com/att-activates-new-4g-lte-markets-expands-coverage-others" target="_blank">read more</a></p>
</description>
<link>
http://www.androidcentral.com/att-activates-new-4g-lte-markets-expands-coverage-others
</link>
<pubDate>Wed, 07 Aug 2013 09:48:24 +0000</pubDate>
<category domain="http://www.androidcentral.com/articles/news">News</category>
<category domain="http://www.androidcentral.com/tags/4g">4g</category>
<category domain="http://www.androidcentral.com/tags/att-0">at&t</category>
<category domain="http://www.androidcentral.com/tags/lte">lte</category>
<guid isPermaLink="false">32622 at http://www.androidcentral.com</guid>
<comments>
http://www.androidcentral.com/att-activates-new-4g-lte-markets-expands-coverage-others#comments
</comments>
<dc:creator>Alex Dobie</dc:creator>
</item>
我的DOM解析器代码是
package com.wfwf.everestnewsapp.parser;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.util.Log;
public class DOMParser {
private RSSFeed _feed = new RSSFeed();
public RSSFeed parseXml(String xml) {
URL url = null;
try {
url = new URL(xml);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
// Create required instances
DocumentBuilderFactory dbf;
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the xml
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
// Get all <item> tags.
NodeList nl = doc.getElementsByTagName("item");
int length = nl.getLength();
Log.i("this is the test message"+length, xml);
for (int i = 0; i < length; i++) {
Node currentNode = nl.item(i);
RSSItem _item = new RSSItem();
NodeList nchild = currentNode.getChildNodes();
int clength = nchild.getLength();
Log.i("this is the test message total child nodes"+clength, xml);
// Get the required elements from each Item
// Ishwor changed the code j=0 and j= j+1
for (int j = 0; j < clength; j = j + 1) {
Log.i("first child node name is"+nchild.item(j).getNodeName(), xml);
Node thisNode = nchild.item(j);
String theString = null;
//ishwor changed as
if (thisNode != null && thisNode.getFirstChild() != null) {
theString = thisNode.getFirstChild().getNodeValue();
}
if (theString != null) {
String nodeName = thisNode.getNodeName();
/*
String nodeName = thisNode.getNodeName();
//theString = nchild.item(j).getFirstChild().getNodeValue();
if(nchild.item(j).getFirstChild().getNodeValue()!=null){
//if (theString != null) {
//String nodeName = thisNode.getNodeName();
*/
if ("title".equals(nodeName)) {
// Node name is equals to 'title' so set the Node
// value to the Title in the RSSItem.
_item.setTitle(theString);
Log.i("this is the test message"+theString, xml);
}
else if ("description".equals(nodeName)) {
_item.setDescription(theString);
Log.i("this is the test message"+theString, xml);
// Parse the html description to get the image url
String html = theString;
org.jsoup.nodes.Document docHtml = Jsoup.parse(html);
Elements imgEle = docHtml.select("img");
_item.setImage(imgEle.attr("src"));
}
else if ("pubDate".equals(nodeName)) {
// We replace the plus and zero's in the date with
// empty string
String formatedDate = theString.replace(" +0000",
"");
_item.setDate(formatedDate);
}
}
}
// add item to the list
_feed.addItem(_item);
}
} catch (Exception e) {
}
// Return the final feed once all the Items are added to the RSSFeed
// Object(_feed).
return _feed;
}
}
我的日志cat错误
08-08 12:52:55.059: W/dalvikvm(3484): threadid=11: thread exiting with uncaught exception (group=0x41a692a0)
08-08 12:52:55.064: E/AndroidRuntime(3484): FATAL EXCEPTION: AsyncTask #1
08-08 12:52:55.064: E/AndroidRuntime(3484): java.lang.RuntimeException: An error occured while executing doInBackground()
08-08 12:52:55.064: E/AndroidRuntime(3484): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-08 12:52:55.064: E/AndroidRuntime(3484): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-08 12:52:55.064: E/AndroidRuntime(3484): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-08 12:52:55.064: E/AndroidRuntime(3484): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-08 12:52:55.064: E/AndroidRuntime(3484): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-08 12:52:55.064: E/AndroidRuntime(3484): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-08 12:52:55.064: E/AndroidRuntime(3484): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-08 12:52:55.064: E/AndroidRuntime(3484): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-08 12:52:55.064: E/AndroidRuntime(3484): at java.lang.Thread.run(Thread.java:856)
08-08 12:52:55.064: E/AndroidRuntime(3484): Caused by: java.lang.NoClassDefFoundError: org.jsoup.Jsoup
08-08 12:52:55.064: E/AndroidRuntime(3484): at com.wfwf.everestnewsapp.parser.DOMParser.parseXml(DOMParser.java:102)
08-08 12:52:55.064: E/AndroidRuntime(3484): at com.wfwf.everestnewsapp.Splash$AsyncLoadXMLFeed.doInBackground(Splash.java:131)
08-08 12:52:55.064: E/AndroidRuntime(3484): at com.wfwf.everestnewsapp.Splash$AsyncLoadXMLFeed.doInBackground(Splash.java:1)
08-08 12:52:55.064: E/AndroidRuntime(3484): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-08 12:52:55.064: E/AndroidRuntime(3484): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-08 12:52:55.064: E/AndroidRuntime(3484): ... 5 more
答案 0 :(得分:0)
试试这个例子......
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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 android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class XMLParsingDOMExample extends Activity {
ArrayList<String> title;
ArrayList<String> description;
ArrayList<String> pubDate;
ItemAdapter adapter1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView list = (ListView) findViewById(R.id.list);
title = new ArrayList<String>();
description = new ArrayList<String>();
pubDate = new ArrayList<String>();
try {
URL url = new URL(
"Your URL");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("title");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
Log.v("title--", ""+ ((Node) nameList.item(0)).getNodeValue());
title.add(""+ ((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("description");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
Log.v("description--", ""+ ((Node) websiteList.item(0)).getNodeValue());
description.add(""+ ((Node) websiteList.item(0)).getNodeValue());
NodeList websiteList1 = fstElmnt.getElementsByTagName("pubDate");
Element websiteElement1 = (Element) websiteList1.item(0);
websiteList1 = websiteElement1.getChildNodes();
pubDate.add(""+ ((Node) websiteList1.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
adapter1 = new ItemAdapter(this);
list.setAdapter(adapter1);
}
class ItemAdapter extends BaseAdapter {
final LayoutInflater mInflater;
private class ViewHolder {
public TextView title_text;
public TextView des_text;
public TextView date_text;
}
public ItemAdapter(Context context) {
// TODO Auto-generated constructor stub
super();
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//@Override
public int getCount() {
return title.size();
}
//@Override
public Object getItem(int position) {
return position;
}
//@Override
public long getItemId(int position) {
return position;
}
//@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = mInflater.inflate(R.layout.mainpage_listitem_activity, parent, false);
holder = new ViewHolder();
holder.title_text = (TextView) view.findViewById(R.id.title_text);
holder.des_text = (TextView) view.findViewById(R.id.des_text);
holder.date_text = (TextView) view.findViewById(R.id.date_text);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.title_text.setText(""+title.get(position));
holder.des_text.setText(""+Html.fromHtml(description.get(position)));
holder.date_text.setText(""+pubDate.get(position));
return view;
}
}
}