intrepidkarthi
intrepidkarthi

Reputation: 3102

Issue in XML parsing in Android

Here is my XML.

 <results keywords="ipod" limit="25">
   <products count="30">
     <product merchant_price="179.99" 
       network_id="2" 
       name = "ipod" 
       retail_price="179.99" />
     <product merchant_price="189.99" 
       network_id="3"
       name="ipod16gb" 
       retail_price="189.99" />
   </products>
</results>

From this I need to fetch the product attributes alone. For that I have done this, I have a written a parser.

String xml = parser.getXmlFromUrl(url); // getting XML from the given URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName("product");
// looping through all item nodes 
for (int i = 0; i < 10; i++) {
    Element e = (Element) nl.item(i);
        // adding each child node to HashMap key => value
    Log.v("test",e.getAttribute("name"));
    }

But I am unable to get the value properly and getting NullPointerException Can anyone point out what I am doing wrong here?

Upvotes: 0

Views: 181

Answers (3)

vin_mobilecem
vin_mobilecem

Reputation: 157

The loop is running 10 times which is more than the nodes present in your xml, that is why you are getting null pointer exception. Try nl.length(use a function which will return lenth of the list ) to get the number of elements in the list of elements you have made through doc.getElementsByTagName("product");.

Upvotes: 1

intrepidkarthi
intrepidkarthi

Reputation: 3102

The issue was with the Xml parser. Corrected it with this while parsing.

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse httpResponse = httpClient.execute(request);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);

Upvotes: 0

mukesh
mukesh

Reputation: 4140

Try it

     Element e = (Element) nl.item(i);
     NamedNodeMap attributes = e.getAttributes();
            for (int a = 0; a < attributes.getLength(); a++) 
       {
            Node theAttribute = attributes.item(a);
          System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
        }

Upvotes: 1

Related Questions