Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Contributor
sripatel
Posts: 18
Registered: ‎07-29-2010
My Device: Not Specified

sax parsing

can any one send me some sample question and answers of sax parsing

Developer
nitinverma274
Posts: 950
Registered: ‎06-22-2010
My Device: 9550

Re: sax parsing

This is the Complete code of sax Parsing.

 

 

package Xml;

import org.w3c.dom.*;
import java.io.*;
import javax.microedition.io.*;
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.jaxp.*;
import net.rim.device.api.xml.parsers.*;
import org.xml.sax.*;

class xmlReader extends MainScreen 
{
    HttpConnection con=null;
    InputStream input=null;
    public xmlReader() 
    {            
        try
        {
            con=(HttpConnection)Connector.open("http://localhost/emp.xml",Connector.READ_WRITE);
            input=con.openInputStream();
            DocumentBuilderFactory fact=DocumentBuilderFactory.newInstance();
            DocumentBuilder build=fact.newDocumentBuilder();
            Document doc=build.parse(input);
            Element root=doc.getDocumentElement();
            root.normalize();
            displayNode(root,0);
        }catch(Exception ex)
        {
            System.out.println(ex.toString());
        }
    }
    
    public void displayNode(Node node,int dep)
    {
        if(node.getNodeType()==Node.ELEMENT_NODE)
        {
            StringBuffer sb=new StringBuffer();
            NodeList child=node.getChildNodes();
            int chil=child.getLength();
            Node firstchild=child.item(0);
            if(chil==1 && firstchild.getNodeType()==Node.TEXT_NODE)
            {
                sb.append(firstchild.getNodeValue());
                sb.append("\n");
                add(new RichTextField(sb.toString()));
                add(new SeparatorField());
            }
            else
            {
                String parentName=node.getNodeName();
                for(int i=0;i<chil;i++)
                {
                    displayNode(child.item(i),dep+1);
                }
            }
        }
        else
        {
            String nodeValue = node.getNodeValue();
            /*if ( nodeValue.trim().length() != 0 ) 
             {
                 StringBuffer sb = new StringBuffer();
                 //indentStringBuffer(sb,dep);
                 sb.append( '"' ).append( nodeValue ).append( '"' );
                 add( new RichTextField(sb.toString()));
                 Dialog.alert("Sorry!No Data Found in the File");
             }*/
        }
    }
} 

 

 

-------------------------------------------------------------------------------------------------------------------------

Press Kudoes To say thanks to User who solved Ur Problems.

Developer
peter_strange
Posts: 19,610
Registered: ‎07-14-2008
My Device: Not Specified

Re: sax parsing

Don't believe that the sample given is SAX parsing.

 

There are numerous examples on the Web of using SAX.  I am not actually aware of a BlackBerry specific example.

 

There are a number of ways of doing it.  Here is one.  I have done this from memory, it could be wrong...

 

a) Create a class that extends XMLParser - actually I don't think you need to do this, but I always do, probably just a habit.  let us call that class MyParser.

b) Create a class that extends DefaultHandler, let us call that class MyHandler.  In this class, you get told as the parser hits key parts of the XML stream, so you get told about the start of an element, the end of an element, and the attributes of an element and so.  You need to convert this into objects that your application will process in here.  I generally implement:
characters
endDocument
endElement
error
fatalError
startDocument
startElement
warning

c) Take your input as a Stream - you will have to use something like this to get a Stream from some bytes or a String that you have:

new InputStreamReader(new ByteArrayInputStream(<xml mesage in bytes>))

Let us call this myInputStream

d) Parse it

MyParser.parser(myInputStream, MyHandler);

Put this code in a try catch and report the exceptions.

 

I think the SAX parser is harder to implement, because you are picking up the XML as you are going, but I believe it is much more efficient and it means you can just extract the parts that you need. 

 

Hope this helps.

Developer
Ted_Hopp
Posts: 1,305
Registered: ‎01-21-2009
My Device: Not Specified

Re: sax parsing

[ Edited ]

I set up my SAX parsing in a little different way than Peter does:

 

SAXParser sp;
try {
SaxParserFactory spf = SAXParserFactory.newInstance();
// configure the factory for the kind of parser you want
sp = spf.newSAXParser();
} catch (Exception e) {
// something wrong with the factory settings
}

 

This provides the option of using a validating parser, which is not possible when instantiating an XMLParser directly.

 

As for handling SAX events, here's a class I use to handle an "envelope" structure to XML documents. The idea of an enveolope is that the top-level document element indicates either success or failure. Failure documents all have the same structure:

<failure>
<code>error code</code>

<details>(optional) detailed message about the failure</details>

</failure>

Success documents have a highly variable structure:

<success>

<!-- success sub-document XML here -->

</success>

Each success sub-document has its own handler. The envelope handler is constructed with a reference to a particular success handler and if the envelope indicates success, relays SAX events to the success handler. (I only need to relay some events; another application might need more complete coverage.) The success handler has no idea that it is receiving events from the envelope handler instead of from the parser directly. Here's the code that does this (ErrorCodes is an interface that just defines a bunch of error code constants):

 

/**
* Envelope handler. This determines whether the document root is
* "success" or "failure". If it is "success", it delegates all internal
* processing to the <code>successHandler</code> passed at creation. If it is
* "failure", then it accumulates the failure error code and details returned
* from the server.
*/
class EnvelopeHandler extends DefaultHandler implements ErrorCodes {
private DefaultHandler successHandler;
boolean failure;
boolean success;
private StringBuffer buff = new StringBuffer();
int errorCode;
String errorDetails;

/**
* Construct an <code>EnvelopeHandler</code> that will delegate success
* document processing to the given handler. If <code>successHandler</code>
* is <code>null</code>, then the body of the success document (if any) will
* be uninterpreted (although it will be parsed).
*
* @param successHandler
* the handler for success documents. A <code>null</code> value
* can be used to handle empty success documents.
*/
EnvelopeHandler(DefaultHandler successHandler) {
this.successHandler = successHandler;
}

public void characters(char[] ch, int start, int length) throws SAXException {
if (failure) {
buff.append(ch, start, length);
} else if (successHandler != null) {
successHandler.characters(ch, start, length);
}
}

/**
* Relays to <code>characters(ch, start, length)</code>. (All white space is
* treated as significant.)
*/
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
characters(ch, start, length);
}

public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
if (success) {
if (successHandler != null)
successHandler.startElement(uri, localName, name, attributes);
} else if ("success".equals(localName)) {
success = true;
} else if ("failure".equals(localName)) {
failure = true;
} else if (!success && !failure) {
// unknown document root element!
throw new SAXParseException("Unknown root element: " + localName);
}
}

public void endElement(String uri, String localName, String name)
throws SAXException {
if (failure) {
if ("code".equals(localName)) {
String code = buff.toString();
buff.setLength(0);
try {
errorCode = Integer.parseInt(code);
} catch (NumberFormatException e) {
errorCode = E_RESPONSE_INDECIPHERABLE;
errorDetails = code;
}
} else if ("details".equals(localName)) {
errorDetails = buff.toString();
buff.setLength(0);
}
} else if (successHandler != null) {
if ("success".equals(localName) || "failure".equals(localName)) {
successHandler.endDocument();
} else {
successHandler.endElement(uri, localName, name);
}
}
}
}
ResponseHandler rh = new ResponseHandler(h);
            SAXParser sp;
            try {
                sp = SAXParserFactory.newInstance().newSAXParser();
            } catch (ParserConfigurationException e) {
                setExceptionError(E_INTERNAL_PARSER_CREATION, e);
                return false;
            } catch (SAXException e) {
                setExceptionError(E_INTERNAL_PARSER_CREATION, e);
                return false;
            }
            try {
                sp.parse(new InputSource(is), rh);
            } catch (SAXException e) {
                setExceptionError(E_RESPONSE_BAD_XML, e);
                return false;
            }



Solved? click "Accept as solution". Helpful? give kudos by clicking on the star.
Contributor
sripatel
Posts: 18
Registered: ‎07-29-2010
My Device: Not Specified

Re: sax parsing

yar ur code is not working , just see the code iam sending u and kindly say me wat is the error,,,,,,

 

 

 

 

import org.w3c.dom.*;
import java.io.*;
import javax.microedition.io.*;

import net.rim.device.api.ui.UiApplication;
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.jaxp.*;
import net.rim.device.api.xml.parsers.*;
import org.xml.sax.*;

public class xmlReader extends UiApplication {

    public xmlReader() {

        pushScreen(new Pars());
    }

    public static void main(String[] args) {
        xmlReader app = new xmlReader();
        app.enterEventDispatcher();
    }
}


class Pars extends MainScreen
{
    HttpConnection con=null;
    InputStream input=null;
    public Pars()
    {            
        try
        {
            con=(HttpConnection)Connector.open("http://www.ayansys.mobi/APTVT_3.0/ServiceType.xml",Connector.READ_WRITE);
            input=con.openInputStream();
            DocumentBuilderFactory fact=DocumentBuilderFactory.newInstance();
            DocumentBuilder build=fact.newDocumentBuilder();
            Document doc=build.parse(input);
            Element root=doc.getDocumentElement();
            root.normalize();
            displayNode(root,0);
        }catch(Exception ex)
        {
            System.out.println(ex.toString());
        }
    }
    
    public void displayNode(Node node,int dep)
    {
        if(node.getNodeType()==Node.ELEMENT_NODE)
        {
            StringBuffer sb=new StringBuffer();
            NodeList child=node.getChildNodes();
            int chil=child.getLength();
            Node firstchild=child.item(0);
            if(chil==1 && firstchild.getNodeType()==Node.TEXT_NODE)
            {
                sb.append(firstchild.getNodeValue());
                sb.append("\n");
                add(new RichTextField(sb.toString()));
                add(new SeparatorField());
            }
            else
            {
                String parentName=node.getNodeName();
                for(int i=0;i<chil;i++)
                {
                    displayNode(child.item(i),dep+1);
                }
            }
        }
        else
        {
            String nodeValue = node.getNodeValue();
            /*if ( nodeValue.trim().length() != 0 )
             {
                 StringBuffer sb = new StringBuffer();
                 //indentStringBuffer(sb,dep);
                 sb.append( '"' ).append( nodeValue ).append( '"' );
                 add( new RichTextField(sb.toString()));
                 Dialog.alert("Sorry!No Data Found in the File");
             }*/
        }
    }
}

Contributor
sripatel
Posts: 18
Registered: ‎07-29-2010
My Device: Not Specified

Re: sax parsing

hi peter thannks for ur acknowledgment , i have developed a code , but iam not getting output in my simulator, could u check out where is the mistake and send me the exact solution for it

 

 

 

import java.io.InputStream;

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

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;

public class SaxParseUrl extends UiApplication {

    public SaxParseUrl() {

        pushScreen(new Pars());
    }

    public static void main(String[] args) {
        SaxParseUrl app = new SaxParseUrl();
        app.enterEventDispatcher();
    }
}

class Pars extends MainScreen implements ContentHandler {
    boolean name;

    Pars() {
        try {
            XMLReader parser = XMLReaderFactory.createXMLReader();
            parser.setContentHandler(this);
            HttpConnection conn = (HttpConnection)Connector.open("http://www.ayansys.mobi/APTVT_3.0/ServiceType.xml");
            InputStream is = conn.openInputStream();
            InputSource iss = new InputSource(is);
            
            parser.parse(iss);
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public void startElement(String nsURI, String strippedName, String tagName,
            Attributes attributes) throws SAXException {
        try {
            if (tagName.equalsIgnoreCase("Service")) {
                name = true;
            }
        } catch (Exception e) {
            System.out.println(e);

        }
    }

    public void characters(char[] ch, int start, int length) {
        if (name) {
            try {
                System.out.println("Title: " + new String(ch, start, length));
            
                    LabelField lb=new LabelField(""+ new String(ch, start, length));
                HorizontalFieldManager sr=new HorizontalFieldManager();
                sr.add(lb);
                add(sr);
        
                    
                    //v_cid.addElement(new String(ch, start, length));
                //System.out.println("the elements of vector: " + v_cid);
                
            
                
                // name = false;
                //Enumeration e = v_cid.elements();
                //System.out.println("The elements of vector: " + v_cid);
                //while (e.hasMoreElements()) {
                    //System.out.println("The elements are: " + e.nextElement());
                //}*/
            } catch (Exception e) {
                System.out.println(e);
            }
        }

    }

    public void endDocument() throws SAXException {

    }

    public void endElement(String uri, String localName, String tagName)
            throws SAXException {
    }

    public void endPrefixMapping(String prefix) throws SAXException {

    }

    public void ignorableWhitespace(char[] ch, int start, int length)
            throws SAXException {

    }

    public void processingInstruction(String target, String data)
            throws SAXException {

    }

    public void setDocumentLocator(Locator locator) {

    }

    public void skippedEntity(String name) throws SAXException {

    }

    public void startDocument() throws SAXException {

    }

    public void startPrefixMapping(String prefix, String uri)
            throws SAXException {

    }
}

Developer
Ted_Hopp
Posts: 1,305
Registered: ‎01-21-2009
My Device: Not Specified

Re: sax parsing

First, you should not be making network connections on the event thread. (You are doing this in the c'tor for Pars.) I suggest you rewrite your c'tor as follows:

 

public Pars() {
new Thread() {
public void run() {
try {
con=(HttpConnection) Connector.open("...", Connector.READ_WRITE);
int rc = con.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("Response code: " + rc);
}
input=con.openInputStream();
DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
DocumentBuilder build = fact.newDocumentBuilder();
Document doc = build.parse(input);
final Element root = doc.getDocumentElement();
Application.getApplication().invokeLater(
new Runnable() {
public void run() {
displayNode(root, 0);
invalidate();
}
}
};
} catch(Exception ex) {
System.out.println(ex.toString());
}
}
}.start();
}

Then you can use the debugger to see whether you are receiving the document you expect. You can also trace through the code to see why you are not getting any screen output.

 

Of course, this is DOM parsing, not SAX parsing. The most common suspect when things aren't working is the logic for navigating the DOM tree. I think that you are trying to walk the tree and add a new RichTextField and separator for every Text node in the tree. If so, I think your logic could be a little simpler:

public void displayNode(Node node, int dep) {
int type = node.getNodeType();
if (type == Node.ELEMENT_NODE) {
NodeList children = node.getChildNodes();
int nChildren = children.getLength();
for (int i = 0; i < nChildren; ++i) {
displayNode(children.item(i), dep + 1);
}
} else if (type == Node.TEXT_NODE) {
StringBuffer sb=new StringBuffer();
sb.append(node.getNodeValue());
sb.append("\n");
add(new RichTextField(sb.toString()));
add(new SeparatorField());
} // ignore all other node types
}



Solved? click "Accept as solution". Helpful? give kudos by clicking on the star.
Contributor
sripatel
Posts: 18
Registered: ‎07-29-2010
My Device: Not Specified

Re: sax parsing

no iam not understanding what to do, iam in between the project and my project leader is on my head to complete today, plz give me complete code relating my code in sax parsing

Developer
Ted_Hopp
Posts: 1,305
Registered: ‎01-21-2009
My Device: Not Specified

Re: sax parsing

In two successive posts, you showd two versions of your parsing code. One uses DOM parsing (with a DocumentBuilder) and was what I was commenting about in my last post. The other uses SAX parsing (with an XMLReader). I take it that you want help with the SAX version.

 

You aren't explaining exactly what is going wrong other than "not getting output in my simulator". That is too vague for someone to offer help. I assume it means that the screen is blank when your app runs. Are your parse handling methods being called? Are you adding fields to the screen? Perhaps you simply need to call invalidate() after adding a field. Are you seeing output from your System.out.println() calls? Is it what you expect? Are you seeing exceptions?

 

Learn to use the debugger to observe what is happening with your code. It will probably give you answers faster than can be obtained on this forum.




Solved? click "Accept as solution". Helpful? give kudos by clicking on the star.
Contributor
sripatel
Posts: 18
Registered: ‎07-29-2010
My Device: Not Specified

Re: sax parsing

hi ya wat u said is right but , iam getting exceptions i have already send u the message