0

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?

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
intrepidkarthi
  • 3,104
  • 8
  • 42
  • 75

3 Answers3

1

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());
        }
mukesh
  • 4,140
  • 5
  • 29
  • 40
1

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");.

Anshu
  • 7,783
  • 5
  • 31
  • 41
  • I have just mentioned 2 elements for sample. There is a lot in real list – intrepidkarthi Oct 04 '12 at 12:05
  • you are getting null pointer exception in e.getNodeName() and e.getAttributes() that means e is null .....print nl.size() .................................................................................. for (int i = 0; i < nl.size(); i++) { Element e = (Element) nl.item(i); // adding each child node to HashMap key => value Log.v("test",e.getAttribute("name")); } – vin_mobilecem Oct 04 '12 at 12:34
0

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);
intrepidkarthi
  • 3,104
  • 8
  • 42
  • 75