Search code examples
javaparsingblackberryblackberry-eclipse-plugin

Parse xml response and display it to main screen in blackberry


I have following kind of xml response from some http://url.com

<ArrayOfMovie>
   <Movie>
      <movieID>7</movieID>
      <name>Badmaash Company</name>
      <starCast> Shahid Kapoor, Anushka Sharma, Meiyang Chang, Vir Das </starCast>
      <releaseDate>2010-05-07</releaseDate>
      <moviePoster>bc/bc.jpg</moviePoster>
      <movieGenere>Drama</movieGenere>
   </Movie>
</ArrayOfMovie>

Now I want to parse this data and display it to blackberry main screen.

I have tried it using kxml and SAXParser. But unfortunately I couldnot parse it properly.

Can anybody help me to solve the above issue with some sample code or tutorial ?

Thanks in advance....


Solution

  • The following snippit of code should enable you to retrieve and parse XML from a URL. It is very basic and has no real handling of potential errors.

    
    import java.io.*;
    import javax.microedition.io.*;
    import net.rim.device.api.xml.parsers.*;
    import org.w3c.dom.Document;
    
    public class Test 
    {
    
        public Document RetreiveXMLDocFromURL(String url) throws IOException
        {
            HttpConnection httpConn = (HttpConnection)Connector.open(url);
            int responseCode = httpConn.getResponseCode();
            Document xmlDoc = null;
    
            if (responseCode == HttpConnection.HTTP_OK)
            {
                try
                {
                    InputStream inputStream = httpConn.openInputStream();
                    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                    xmlDoc = docBuilder.parse(inputStream);                 
                }
                catch(Exception ex)
                {
                    //error handling
                }                               
            }
            else        
            {
                //error handling
            }
    
            return xmlDoc;
        }
    }