0

i using the follwing Code to retrive XML element text using getElementsByTagName

this code success in 2.2 and Failed in 2.1

any idea ?

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(); // 
Cesar
  • 3,519
  • 2
  • 29
  • 43
yaniv
  • 1
  • 3
  • format it properly in order to get good answers. ;-P – Ben Weiss Dec 30 '10 at 21:35
  • it's really strange there is a difference between 2.1 and 2.2. Are you sure you are using the same code AND the same server response? Also what is the stack trace? It should point to some reason. – Vit Khudenko Dec 30 '10 at 22:03

1 Answers1

4

getTextContent() is not supported in API 7 (Android 2.1). It was introduced in API 8 (2.2).

Assuming a predictable result from the server, you can use the following code:

Node n = aNodeList.item(i);

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

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

If the element may be empty, then you'd want to check the child count first.

paiego
  • 3,619
  • 34
  • 43
  • This assumes the child will be a single text node. I just ran into a case where there was a Unicode entity (accented character é) appearing as `é` in the text content. The parser split the string up into several text nodes, so I had to loop and concatenate them to get the equivalent functionality of `getTextContent()` from API version 8. (Of course, due to bug [#2607](http://code.google.com/p/android/issues/detail?id=2607), unicode entities simply don't show up.) – Mike Mueller Sep 19 '11 at 19:25