Wednesday, February 18, 2009

How To - Use the XML Parser


XML (Extensible Markup Language) documents allow developers to represent complex data in a simple manner. Developers can completely define their data in XML because it provides fully customized tags. In XML, there are no predefined or hard-coded tags like there are in HTML documents.

The net.rim.device.api.xml.jaxp.XMLParser API allows developers to leverage XML advantages on the BlackBerry platform. This new BlackBerry JDE 4.0 API allows developers to parse XML content and customize the point of view on BlackBerry devices. The sample provided below uses a static web-based XML document and parses through it to display the tag name with its corresponding data values.

import javax.microedition.io.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;
import net.rim.device.api.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;

class XML_Parsing_Sample extends UiApplication{
//creating a member variable for the MainScreen
MainScreen _screen= new MainScreen();

//string variables to store the values of the XML document
String _node,_element;
Connection _connectionthread;

public static void main(String arg[]){
XML_Parsing_Sample application = new XML_Parsing_Sample();
//create a new instance of the application
//and start the application on the event thread
application.enterEventDispatcher();
}

public XML_Parsing_Sample() {
_screen.setTitle("XML Parsing");//setting title
_screen.add(new RichTextField("Requesting....."));
_screen.add(new SeparatorField());
pushScreen(_screen); // creating a screen

//creating a connection thread to run in the background
_connectionthread = new Connection();
_connectionthread.start();//starting the thread operation
}

public void updateField(String node, String element){
//receiving the parsed node and its value from the thread
//and updating it here
//so it can be displayed on the screen
String title="Title";
_screen.add(new RichTextField(node+" : "+element));
if(node.equals(title)){
screen.add(new SeparatorField());
}
}

private class Connection extends Thread{
public Connection(){
super();
}

public void run(){
// define variables later used for parsing
Document doc;
StreamConnection conn;
try{
//providing the location of the XML file,
//your address might be different
conn=(StreamConnection)Connector.open
("http://localhost:8000/content/test.xml;deviceside=true");

//next few lines creates variables to open a
//stream, parse it, collect XML data and
//extract the data which is required.
//In this case they are elements,
//node and the values of an element
DocumentBuilderFactory docBuilderFactory
= DocumentBuilderFactory. newInstance();
DocumentBuilder docBuilder
= docBuilderFactory.newDocumentBuilder();
docBuilder.isValidating();
doc = docBuilder.parse(conn.openInputStream());
doc.getDocumentElement ().normalize ();
NodeList list=doc.getElementsByTagName("*");
_node=new String();
_element = new String();
//get the event lock to avoid IllegelStateException while accessing the UI
Object obj = Application.getEventLock();
//this "for" loop is used to parse through the
//XML document and extract all elements and their
//value, so they can be displayed on the device
for (int i=0;i<list.getLength();i++){
synchronized(obj){
Node value=list.item(i).
getChildNodes().item(0);
_node=list.item(i).getNodeName();
_element=value.getNodeValue();
updateField(_node,_element);
}
}//end for
}//end try
//will catch any exception thrown by the XML parser
catch (Exception e){
System.out.println(e.toString());
}
}//end connection function inside run
}// end connection class
}//end XML_Parsing_Sample

16 comments:

  1. This was helpful.

    Do you have a sample test.xml file?

    ReplyDelete
  2. yeah same question....text.xml??

    ReplyDelete
  3. You can take default xml file as sample that comes with JDE. You can find it in following Path:

    "c:\Program Files\Research In Motion\BlackBerry JDE 4.x.x\samples\com\rim\samples\device\xmldemo\xml\bookstore.xml"

    ReplyDelete
  4. How to import XML file in JDE....sorry i am new in JDE..Thanks in advance

    ReplyDelete
  5. You can put XML file to your project location and use it like as follows :

    InputStream inputStream = getClass().getResourceAsStream("/res/myXmlFile.xml");
    Document document = builder.parse( inputStream );

    for more info plz see the sample application named 'xmldemo' that comes with JDE.

    ReplyDelete
  6. How to get data from xml file if xml file is not added in project...if xml placed over the network

    ReplyDelete
  7. If xml file is over the network then you have to pass the network path to the Connector.

    conn=(StreamConnection)Connector.open
    ("network path here");

    See Above example.

    ReplyDelete
  8. Thanx..
    but dnt know y
    (StreamConnection)Connector.open ("http://localhost/text.xml")is not working...and also not give any error or exception.
    connThred.get(url) is working fine..even inputstream also .....can i use inputStream for network file???

    ReplyDelete
  9. Now i have done it..:)...Thank u very much...

    ReplyDelete
  10. The connection is not working, is there something else I need to do? It catches some exception during the try catch statement. How else could I connect to an http address with an xml file?

    ReplyDelete
  11. hello..i have found trouble the data cannot retrieve on the simulator...MDS running fine...im using apache php

    here's the code i just modified connection url

    "http://localhost:8888/bb/bookstore.xml"

    ReplyDelete
  12. Hi maverickfastern, modify your URL like,
    ""http://localhost:8080/bb/bookstore.xml;deviceside=true" and run the application

    ReplyDelete
  13. Hi
    I tried this example with eclipse + blackberry 5.0 environment (9550 simulator). I'm getting the following output.

    ----------------------
    XML Parsing
    Requesting.....




    ----------------------
    thats it. nothing is displaying after wards. I am new to blackberry. Could you let me know how to test this example.

    ReplyDelete
  14. Hello,

    I tried your example with an url (XML files over http). But i am not getting any data except the title and requesting... label.

    Could you let me know where i have to make changes to get the data.

    Thanks in advance.

    ReplyDelete

Place your comments here...