22 Replies Latest reply: Aug 1, 2011 8:59 AM by isebastian RSS

[ask] XML parsing

isebastian Newbie
<?XML version="1.0"?>
<root><pelayanan><id_pelayanan>7</id_pelayanan><nama_pelayanan>Eagle kids Volunteer</nama_pelayanan></pelayanan><pelayanan><id_pelayanan>6</id_pelayanan><nama_pelayanan>Volunteer IT</nama_pelayanan></pelayanan><pelayanan><id_pelayanan>5</id_pelayanan><nama_pelayanan>Usher Umum</nama_pelayanan></pelayanan><pelayanan><id_pelayanan>4</id_pelayanan><nama_pelayanan>Pendoa</nama_pelayanan></pelayanan><pelayanan><id_pelayanan>3</id_pelayanan><nama_pelayanan>Multimedia</nama_pelayanan></pelayanan><pelayanan><id_pelayanan>2</id_pelayanan><nama_pelayanan>Creative Ministry</nama_pelayanan></pelayanan><pelayanan><id_pelayanan>1</id_pelayanan><nama_pelayanan>Praise and Worship</nama_pelayanan></pelayanan></root>

 that's my XML

 

my question is:

how to read it on my blackberry and display it? 

 

 

can i get the data as String type?

 

thank you very much

 

hope you can help me Smiley Happy

 

sorry for my bad english 

 

 

 

package mypackage;
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
        System.out.println("lalalala");
        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/ms/write.xml");
                //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();
                //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++){
                    Node value=list.item(i).
                      getChildNodes().item(0);
                    _node=list.item(i).getNodeName();
                    _element=value.getNodeValue();
                    updateField(_node,_element);
                    System.out.print(_node);
                }//end for
            }//end try
            //will catch any exception thrown by the XML parser
            catch (Exception e){
                System.out.println(e.toString());
            }
        }//end connection function
    }// end connection class
}

 i used that source code, but nothin displayed.... 

 

and don't forget, i'm a new programming in blackberry device, so, i'm so thank to you if you can explain it in the "simple" explanation Smiley Happy

 

God Bless

  • Re: [ask] XML parsing
    peter_strange Master

    This KB article will help you parse the data:

    Use the XML Parser

     

    Regarding displaying it, there are many many options here and we have no idea what you want.  I think you should review some of the sample applications.  You will probably also find these tutorials helpful.

     

    BlackBerry Java Development Environment Tutorials

     

    Once you have a better idea what you want and what can be done, please ask again.

     

    Good luck

    • Re: [ask] XML parsing
      isebastian Newbie

      hi peter, how are you?

       

      thanks for reply..

       

      package mypackage;
      import javax.microedition.io.*;
      import javax.wireless.messaging.Message;
      
      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() {
           _connectionthread = new Connection();
              _connectionthread.start();//starting the thread operation
              _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/ms/write.xml");
                      //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("root");
                      
                      
                      _node=new String();
                      _element = new String();
                      int n = list.getLength();
                      String[] choices= new String[n];
                      //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++){
      //                    Node value=list.item(i).
                       choices[i] =list.item(i).getFirstChild().getNodeValue();
      //                      getChildNodes().item(0);
      //                    _node=list.item(i).getNodeName();
      //                    _element=value.getNodeValue();
      //                    updateField(_node,_element);
                          Dialog.inform(choices[1]);
                      }//end for
                  }//end try
                  //will catch any exception thrown by the XML parser
                  catch (Exception e){
                      System.out.println(e.toString());
                  }
              }//end connection function
          }// end connection class
      }

       i've done that code already, but nothin showed up.

      i think there's somethin wrong with my code (the bold one)

       

      and i just confuse, there are 2 methods to parsing xml, DOM and SAX. 

      i don't know what are they... and how to use them.. 

       

      can you help me pleaseee peter Smiley Sad

       

      appriciate your help

      • Re: [ask] XML parsing
        peter_strange Master

        "I've done that code already, but nothing showed up.

        I think there's something wrong with my code (the bold one)"

         

        Not sure what you mean here, didn't see any bold.

         

        ANyway, can I suggest that you develop your program is phases.  There appear to be at least 3 in this case:

         

        a) Get data from the Server

        b) parse the data as it is XML

        c) Display the data.

         

        If you are struggling with (a), then changing (B0 is not going to be visible, unless you build a test rig and feed the data directly in.  This is actually what I typically do, I will bypass the http call and supply test data directly.  It is easy to add test data to you app, this is one way:

        Add plain text or binary files to an application

         

        "there are 2 methods to parsing xml, DOM and SAX. "

         

        Regarding DOM verses SAX, that is something that is not Blackberry specific so not really a focus for this forum.  There are plenty of XML information on the web, I suggest you have a look around.  But in summary, DOM will build a big Object from your XML data, which you can then query, SAX will use callbacks into your own program for each element and attribute found, and so you can build your own data from it.  I have always used SAX, since I believe it is a little more efficient and I actually typically know what data I am looking for and how I want to display it.  However if you are not sure, and want to parse and then figure it out, then DOM is the way to go. 

        • Re: [ask] XML parsing
          isebastian Newbie

          what i meant with the bold was

           

          NodeList listOfRecord = doc.getElementsByTagName("root");

           "root" is my node

           

          this's my XML file:

          <root>
          <pelayanan>
          <id_pelayanan>7</id_pelayanan>
          <nama_pelayanan>Eagle kids Volunteer</nama_pelayanan>
          </pelayanan>
          <pelayanan>
          <id_pelayanan>6</id_pelayanan>
          <nama_pelayanan>Volunteer IT</nama_pelayanan>
          </pelayanan>
          <pelayanan>
          <id_pelayanan>5</id_pelayanan>
          <nama_pelayanan>Usher Umum</nama_pelayanan>
          </pelayanan>
          <pelayanan>
          <id_pelayanan>4</id_pelayanan>
          <nama_pelayanan>Pendoa</nama_pelayanan>
          </pelayanan>
          <pelayanan>
          <id_pelayanan>3</id_pelayanan>
          <nama_pelayanan>Multimedia</nama_pelayanan>
          </pelayanan>
          <pelayanan>
          <id_pelayanan>2</id_pelayanan>
          <nama_pelayanan>Creative Ministry</nama_pelayanan>
          </pelayanan>
          <pelayanan>
          <id_pelayanan>1</id_pelayanan>
          <nama_pelayanan>Praise and Worship</nama_pelayanan>
          </pelayanan>
          </root>

           

          from that xml , i want to get String which has value like:

          7

          Eagle Kids Volunteer

          6

          Volunteer IT

          etc...

           

          but, it has to be a String, so i can show it in my screen application..

           

          please help me peter Smiley Happy

           

          package mypackage;
          
          import java.io.IOException;
          import java.io.InputStream;
          
          import javax.microedition.io.Connector;
          import javax.microedition.io.HttpConnection;
          import javax.microedition.io.StreamConnection;
          
          import net.rim.device.api.ui.component.Dialog;
          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.Element;
          import org.w3c.dom.Node;
          import org.w3c.dom.NodeList;
          
          
          /**
           * The main screen for the application.  Displays the results of parsing the XML file.
           */
          public final class XMLDemoScreen extends MainScreen
          {
              // Statics -------------------------------------------------------------------------------------
              private static String _xmlFileName = "/xml/index.xml";
              
              // Constants -----------------------------------------------------------------------------------
              private static final int _tab = 4;
              
              
              /**
               * This constructor parses the XML file into a W3C DOM document, and displays it 
               * on the screen.
               * 
               * @see Document
               * @see DocumentBuilder
               * @see DocumentBuilderFactory
               */
              public XMLDemoScreen() 
              {
                  setTitle("XML Demo");
                  Document doc;
                  try 
                  {
                   Dialog.inform("TRY");
                      // Build a document based on the XML file.
          //            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
          //            DocumentBuilder builder = factory.newDocumentBuilder();
                      
                      StreamConnection stream = (StreamConnection)Connector.open("http://192.168.1.104/ms/lala.xml");
                      Dialog.inform("Setelah connector");
                      
                      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory. newInstance(); 
                    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
                    docBuilder.isValidating();
                    docBuilderFactory.setExpandEntityReferences(true);
             docBuilderFactory.setIgnoringComments(true);
             docBuilderFactory.setNamespaceAware(false);  
                    doc = docBuilder.parse(stream.openInputStream());
                    doc.getDocumentElement ().normalize ();
                    String message = doc.getDocumentURI().toString();
                    
          //          NodeList list=doc.getElementsByTagName("root");
                    
                      
          //            InputStream inputStream = getClass().getResourceAsStream( _xmlFileName );
                       
                      Dialog.inform("Setelah Input Stream");
                      // Normalize the root element of the XML document.  This ensures that all Text 
                      // nodes under the root node are put into a "normal" form, which means that 
                      // there are neither adjacent Text nodes nor empty Text nodes in the document.
                      // See Node.normalize().
          //            Element rootElement = doc.getDocumentElement();
          //            rootElement.normalize();
                      NodeList listOfRecord = doc.getElementsByTagName("root");
                      int total =listOfRecord.getLength();
                      
                      Dialog.inform("TRY BAWAH");
                      // Display the root node and all its descendant nodes, which covers the entire
                      // document.
                      
                      for(int i=0 ; i<total; i++){
                       Element myElement = (Element) listOfRecord.item(i);
                       
                       String root = myElement.getAttribute("root");
                      }
                  } 
                  catch ( Exception e ) 
                  {
                      System.out.println( e.toString() );
                  }
              }
              
              
              /**
               * Displays a node at a specified depth, as well as all its descendants.
               * 
               * @param node The node to display.
               * @param depth The depth of this node in the document tree.
               */
              private void displayNode( Node node, int depth ) 
              {        
                  // Because we can inspect the XML file, we know that it contains only XML elements
                  // and text, so this algorithm is written specifically to handle these cases.  
                  // A real-world application will be more robust, and will handle all node types. 
                  // See the entire list in org.w3c.dom.Node.      
                  // The XML file is laid out such that each Element node will either have one Text 
                  // node child (e.g. <Element>Text</Element>), or >= 1 children consisting of at 
                  // least one Element node, and possibly some Text nodes.  Start by figuring out
                  // what kind of node we're dealing with.
                  if ( node.getNodeType() == Node.ELEMENT_NODE ) 
                   
                  {
                   Dialog.inform("IF");
                      StringBuffer buffer = new StringBuffer();
                      indentStringBuffer( buffer, depth );
                      NodeList childNodes = node.getChildNodes();
                      int numChildren = childNodes.getLength();
                      Node firstChild = childNodes.item( 0 );
                      
                      // If the node has only one child and that child is a Text node, then it's of 
                      // the form  <Element>Text</Element>, so print 'Element = "Text"'.
                      if ( numChildren == 1 && firstChild.getNodeType() == Node.TEXT_NODE ) 
                      {
                          buffer.append( node.getNodeName() ).append( " = \"" ).append( firstChild.getNodeValue() ).append( '"' );
                          add( new RichTextField( buffer.toString() ) );
                      } 
                      else 
                      {
                          // The node either has > 1 children, or it has at least one Element node child. 
                          // Either way, its children have to be visited.  Print the name of the element
                          // and recurse.
                          buffer.append( node.getNodeName() );
                          add( new RichTextField( buffer.toString() ) );
                          
                          // Recursively visit all this node's children.
                          for ( int i = 0; i < numChildren; ++i ) 
                          {
                              displayNode( childNodes.item( i ), depth + 1 );
                          }
                      }
                  } 
                  else 
                  {
                      // Node is not an Element node, so we know it is a Text node.  Make sure it is 
                      // not an "empty" Text node (normalize() doesn't consider a Text node consisting
                      // of only newlines and spaces to be "empty").  If it is not empty, print it.
                      String nodeValue = node.getNodeValue();
                      if ( nodeValue.trim().length() != 0 ) 
                      {
                          StringBuffer buffer = new StringBuffer();
                          indentStringBuffer( buffer, depth );
                          buffer.append( '"' ).append( nodeValue ).append( '"' );
                          add( new RichTextField( buffer.toString() ) );
                      }
                  }
                  
              }
              
              public String getXml(String url){
               String xml = new String();
               try {
                StreamConnection s = null;
                      s = (StreamConnection)Connector.open(url);
                      HttpConnection httpConn = (HttpConnection)s; 
                
                int status = httpConn.getResponseCode();
                if (status == HttpConnection.HTTP_OK){
                          InputStream input = s.openInputStream();
                          Dialog.inform("HTTP OKay");
                          byte[] data = new byte[256];
                          int len = 0;
                          int size = 0;
                          StringBuffer raw = new StringBuffer();
                              
                          while ( -1 != (len = input.read(data)) ){
                           raw.append(new String(data, 0, len));
                              size += len;    
                          }
                          xml = raw.toString();
                            
                          input.close();
                }
               } catch (IOException e) {
                //Control de la excepcion de la conexion al servidor
                e.printStackTrace();
               }
               return xml;
              }
          
              
              /**
               * Adds leading spaces to the provided string buffer according to the depth of 
               * the node it represents.
               * 
               * @param buffer The string buffer to add leading spaces to.
               * @param depth The depth of the node the string buffer represents.
               */
              private static void indentStringBuffer( StringBuffer buffer, int depth ) 
              {
                  int indent = depth * _tab;
                  
                  for ( int i = 0; i < indent; ++i ) 
                  {
                      buffer.append( ' ' );
                  }
              }
          }
          
          

           i guess, the code is for DOM parser, am i right?

           

           

          how bout this parser:

           

          private void parseResults( String xml ){
                  
                  SAXParserImpl saxparser = new SAXParserImpl();
                  ResponseHandler handler = new ResponseHandler();
                  ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes());
                  try { 
                      saxparser.parse( stream, handler );
                  } catch ( Exception e ) {
                      e.printStackTrace();
                      response.setText( "Unable to parse response.");
                  }      
                  response.setText( handler.response );
              }
          
          

           and the defaultHandler:

          package com.sts.example;
          
          import org.xml.sax.SAXException;
          import org.xml.sax.helpers.DefaultHandler;
          import org.xml.sax.Attributes;
          
          
          /**
           * 
           */
          public class ResponseHandler extends DefaultHandler {
            
              String builder;
              String temp;
              
              public void startDocument() throws SAXException {}
              
              public void startElement(String uri, String name, String qName, Attributes atts){
              if ("".equals(uri)){
              System.out.println("Start element: " + qName);
              }
              temp = "";
              }
              
              public void endElement(String uri, String name, String qName){
              if ("".equals(uri)){
              System.out.println("End element: " + qName);
              }
              }
              
              public void characters(char buf[],int offset,int len) throws SAXException {
                  temp="";
                  String temp2;
                  temp2 = new String(buf, offset, len).trim();
                  if (!temp2.equals("") || !temp2.equals(" ")){
                      temp = temp2;
                  }
                  else{
                      temp = "";
                  }
              }
              
              public void endDocument() throws SAXException {}
          
          }

           can i use it for my XML file?

          • Re: [ask] XML parsing
            peter_strange Master

            Sorry I don't have time to go through that amount of code.  Remember I suggested you split the processing into three parts.

             

            a) Get data from the Server

            b) parse the data as it is XML

            c) Display the data.

             

            If you have done that, then can you tell us if you are actually correctly getting your XML data and if you are parsing it properly.  Isolate exactly where your problem is and just show us code related to that and then it is easier for people like me to help you. 

            • Re: [ask] XML parsing
              isebastian Newbie

              thanks peter_strange

              i've done till the a part

              but i don't know what is goin on with my code.. i debugged my code and it stoped at:

              doc = docBuilder.parse(inputStream);
              doc.getDocumentElement ().normalize ();
              NodeList list=doc.getElementsByTagName("root");

               

               



              it couldn't sout anything...

              • Re: [ask] XML parsing
                peter_strange Master

                Can you dump out what is in inputStream?

                • Re: [ask] XML parsing
                  isebastian Newbie

                  i can't, because it's hang.. it returned nothin....

                  this is my inputstream

                  try{
                  
                  
                  //providing the location of the XML file,
                  //your address might be different
                  conn=(StreamConnection)Connector.open
                  ("http://192.168.1.101/ms/lala.xml"); -->> i can opened it from browser
                  //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();
                  System.out.println("masuk Sini");
                  InputStream inputStream = conn.openInputStream(); --> it's stuck here!!!!!
                  System.out.println(inputStream.read());
                  DocumentBuilder docBuilder= docBuilderFactory.newDocumentBuilder();
                  docBuilder.isValidating();
                  System.out.println("dan sini");
                  docBuilderFactory.setIgnoringElementContentWhitespace(true);
                  // Element root= doc.getDocumentElement(); --> don't know what it is
                  // Element operation = (Element) root.getOwnerDocument(); --> same
                  // String layer = operation.getAttribute("Category");- - > same
                  System.out.println("terakhir");
                  // System.out.println("Category:"+layer);
                  doc = docBuilder.parse(inputStream); --
                  doc.getDocumentElement ().normalize ();
                  NodeList list=doc.getElementsByTagName("root");
                  System.out.println("Atleast!");
                  • Re: [ask] XML parsing
                    peter_strange Master

                    Now you understand why I said to separate your processing out - you thought you had a parser problem, it seems you have a communication problem.

                     

                    I suggest that you review the httpdemo that comes with your toolkit.  See if you can review its processing and get it to read the XML from the URL you have here.  Then when you can do that, you can move onto phase 2, the XML. 

                     

                    But get the data from the Server into a byte array and the pass this to the parser as a ByteArrayinputStream. 

                     

                    Good luck.

  • Re: [ask] XML parsing
    peter_strange Master

    Does this mean you have solved your problem?