Friday, April 9, 2010

XML parsing in Blackberry

package com.rim.androidxml;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.xml.parsers.DocumentBuilder;
import net.rim.device.api.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class First extends UiApplication{
public static void main(String[] args)
{
First theapp = new First();
theapp.enterEventDispatcher();
}
public First()
{
pushScreen(new firstxml());
}
}
class firstxml extends MainScreen
{
public firstxml()
{

try
{
HttpConnection conn = null;
String url = "http://www.updatedpics.com/pics/ucatxml.php?catid=46";//URL of web Service
conn = (HttpConnection)Connector.open(url);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.isValidating();
Document doc = builder.parse(conn.openInputStream());
org.w3c.dom.Element rootElement = doc.getDocumentElement();
rootElement.normalize();
NodeList list = doc.getElementsByTagName("image1");
for(int i=0;i {
Node nd = list.item(i);
if(nd.getNodeType()!=Node.TEXT_NODE)
{
NodeList ndlist = nd.getChildNodes();
for(int k =0;k {
Node nd1 = ndlist.item(k);
if(nd1.getNodeType()!=Node.TEXT_NODE)
{
NodeList nd1list = nd1.getChildNodes();
for(int j=0;j {
Node ddetailnode = nd1list.item(j);
if(ddetailnode.getNodeType()!=Node.TEXT_NODE)
{
if(ddetailnode.getNodeName().equalsIgnoreCase("catname"))
{
add(new RichTextField(getNodeValue(ddetailnode))
{
public void paint(Graphics g)
{
g.setColor(Color.ORANGE);
super.paint(g);
}
});
}
if(ddetailnode.getNodeName().equalsIgnoreCase("name"))
{
add(new RichTextField(getNodeValue(ddetailnode))
{
public void paint(Graphics g)
{
g.setColor(Color.BLUE);
super.paint(g);
}
});


}
}
}
}
}
}
}


}
catch(Exception e)
{}
}
public String getNodeValue(Node node)
{
NodeList nodeList = node.getChildNodes();
Node childNode = nodeList.item(0);
return childNode.getNodeValue();
}
}

NOTE:- No. of loop depends upon no.of tags before the tags which you want to read.
Sorry i can't make everyline as comment so understand on your behalf.

1 comment: