KXML2 with J2ME

I will cover how to use kxml 2 parser with J2ME midlet. I will assume that you are aware with xml and J2ME.

I will explain kxml and then will show example of kxml with J2ME.

Basically kxml 2 implements the XMLPull Parser API. Pull parser is useful when require fast and a small XML parser.
It should be used when all the process has to be performed quickly and efficiently to input elements. We can say kxml is the J2ME Parser.

Now I will show you example of parsing simple xml using kxml.

Test.xml

<order>
<book>Maths</book>
<book price="5">English</book>
</order>

J2ME Implementation using kxml parser for parsing above xml:
try {
File file = new File("C:\\TmintNewCodeTree\\QuartzSample\\resources\\Test1.xml");
InputStream in = new FileInputStream(file);
InputStreamReader is = new InputStreamReader(in);
KXmlParser parser = new KXmlParser();
parser.setInput(is);

parser.nextTag();
parser.require(XmlPullParser.START_TAG, null, "order");

while (parser.next() != XmlPullParser.END_DOCUMENT) { //parser.nextTag()
if (parser.getEventType() == XmlPullParser.START_TAG) {
System.out.println("start tag: " + parser.getName()+" Att count: "

+ parser.getAttributeCount() + "Book name:"+parser.nextText());

if(parser.getAttributeCount()>0){

System.out.println(" Value:"+parser.getAttributeValue(0));

}

}

}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

In above implementation we are iterating xml file till last tag. Then we are checking
if current tag is start tag then do something.

next() or nextTag() advances to next tag. nextTag() advances to the next start or end tag,
skipping insignificant events such as white space, comments.

nextText() requires that the current position is a start tag. It returns the text content of the
corresponding element. The post condition for nextText() is that the current position is an end tag.

public class KXMLSample extends MIDlet {
  KXmlParser parser = null;

   public void startApp() {
      InputStream in = this.getClass().getResourceAsStream("//order.xml");
      InputStreamReader is = new InputStreamReader(in);
      parser = new KXmlParser();
        try {
            parser.setInput(is);
           
                parser.nextTag();
           
        parser.require(XmlPullParser.START_TAG, null, "order");


        while (parser.next() != XmlPullParser.END_DOCUMENT) {
        if (parser.getEventType() == XmlPullParser.START_TAG) {
                
                     System.out.println("start tag: " + parser.getName()+"  Att count:  "
                        + parser.getAttributeCount() + parser.nextText());
            if(parser.getAttributeCount()>0){
                System.out.println("Attr Name:"+parser.getAttributeName(0)+" Value: "+parser.getAttributeValue(0));
            }
        }
        }
            
        } catch (XmlPullParserException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } 
    }

  protected void pauseApp(){}

  protected void destroyApp(boolean unconditional){
    notifyDestroyed();
  }
}


Have u ever used ibotta app for rebate? Try it..Use aydtcuy and you will be added to my team, we can earn fast by making team and generating bonus..Worth it..

© 2009 chirag272003

More by this Author

  • Date Parsing And Date Formatting In JSP Using JSTL
    4

    I have faced problem and i found solution after lots of googling. So may be this will help others when they faced this kind of requirement. Many times we come across a situation where we want to create java.util.Date...

  • Spring Web Service
    13

    Spring Web Service I will assume that you are aware with Spring and basics of web service. I will show you how to develop web service using Spring. Spring uses contract-first approach for developing web service....


Comments 10 comments

farshid 7 years ago

when i transfer and install it into my mobile phone then i receive an unhand led exception!!

just i compile and move it!


chirag272003 profile image

chirag272003 7 years ago Author

It may be possible that your mobile is not supporting KXML or xml file that you specified is not found at given location.


farshid 7 years ago

this is not first time that i use kxml in my mobile!

before i used from kxml1.2.1 in my mobile and it worked good!

i used from this line in my code to reading xml file

InputStream in = this.getClass().getResourceAsStream("//order.xml");

mobile model:6120 classic (OS:Symbian9.2)


chirag272003 profile image

chirag272003 7 years ago Author

Can you please paste whole error stack trace that you get? So that i can give you more precise answer. One more thing your order.xml should be inside resources folder.

Thanks.


hallowady@hotmail.it 6 years ago

I apologize but I have a problem:

I can not open the file that I need to do the parser.

I tried with FileConnection, but says that I have't permission to open the file, since MIDP can not have access to the C:

using "getResurceAsStream ()" return 'null'. where it should be the file to open it with "getResourceAsStream ()"?

Thank you in advance


Moaath 6 years ago

Thanx Man.


veejayc 6 years ago

Thanks...


nam 5 years ago

Thanks . please fix this error :

org.xmlpull.v1.XmlPullParserException: unexpected type (position:TEXT order>

@2:1 in java.io.InputStreamReader@f828ed68)

at org.kxml2.io.KXmlParser.exception(+47)

at org.kxml2.io.KXmlParser.nextTag(+47)

at HttpTest1.startApp(+205)

at javax.microedition.midlet.MIDletProxy.startApp(+7)

at com.sun.midp.midlet.Scheduler.schedule(+270)

at com.sun.midp.main.Main.runLocalClass(+28)

at com.sun.midp.main.Main.main(+80)

com.sun.midp.io.ResourceInputStream@ea0ef881


mutuku 4 years ago

hi, am using kxml to parse data with post method. its working but after a number of requests, it gives a tcpip tokens limit error. any help please??


Bryan 4 years ago

I can't configured Eclipse Indigo IDE and Netbeans 7.1 intergrated kxml and when I code inport org.kxml2.* is error

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working