解析器2.1和2.2

时间:2010-12-30 21:32:04

标签: android xml parsing

我使用以下代码使用getElementsByTagName

检索XML元素文本

此代码在2.2中成功,在2.1中失败

任何想法?

URL metafeedUrl = new URL("http://x..../Y.xml")
URLConnection connection ;     
connection= metafeedUrl.openConnection();

HttpURLConnection  httpConnection = (HttpURLConnection)connection ;        
int resposnseCode= httpConnection.getResponseCode() ;

if (resposnseCode == HttpURLConnection.HTTP_OK) {

InputStream in = httpConnection.getInputStream();

DocumentBuilderFactory dbf ;
dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder db = dbf.newDocumentBuilder();


// Parse the Earthquakes entry 
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();

//ArrayList<Album> Albums = new ArrayList<Album>();


/* Returns a NodeList of all descendant Elements with a given tag name, in document order.*/

NodeList nl = docEle.getElementsByTagName("entry");

if (nl!=null && nl.getLength() > 0) {        
   for (int i = 0; i < nl.getLength(); i++) {

Element entry = (Element)nl.item(i);

/* Now on every property in Entry **/

Element title =(Element)entry.getElementsByTagName("title").item(0);          

*Here i Get an Error*
String album_Title = title.getTextContent();

Element id =(Element)entry.getElementsByTagName("id").item(0);         
String album_id = id.getTextContent(); // 

1 个答案:

答案 0 :(得分:4)

API 7(Android 2.1)不支持

getTextContent()。它是在API 8(2.2)中引入的。

假设服务器有可预测的结果,您可以使用以下代码:

Node n = aNodeList.item(i);

String strValue = n.getFirstChild().getNodeValue();

// as opposed to the String strValue = n.getTextContent();

如果元素可能为空,那么您首先要检查子计数。