Parse XML using jsr172

Source: Internet
Author: User
Tags xml parser

 

This article describes how to use APIs provided by JSR 172 to parse XML.

We know that jsr172 is composed of two parts:
1. A lightweight standard XML Parser
2. Remote API call for Web Services
The lightweight XML Parser implemented in jsr172 is a subset of jaxp1.2 (Java API for XML processing. We can check the APIS provided by wtk to see that there are only 12 classes provided by the j2me-xml, which shows that this lightweight XML parser is suitable for running on resource-constrained devices such as mobile phones.

The following example shows how to use JSR 172 to parse XML. First, we need to prepare an XML file for the project. The content is as follows:

Nokia 7610
Black

It is worth noting that when an XML file contains Chinese characters, we should use text tools, such as NotePad or ultral edit, to convert it into a UTF-8 encoded file, otherwise, the parsing result will contain garbled characters.

To save the information in the XML file, we construct a common Java phone class, which contains two member variables corresponding to name and color respectively. The Code is as follows:
Package example; </P> <p> public class phone {<br/> private string color = ""; <br/> private string name = ""; <br/> Public String getcolour () {<br/> return color; <br/>}</P> <p> Public void setcolour (string color) {<br/> This. color = color; <br/>}</P> <p> Public String getname () {<br/> return name; <br/>}</P> <p> Public void setname (string name) {<br/> This. name = Name; <br/>}</P> <p> Public phone () {<br/>}< br/>

In JSR 172, a sax Parser is implemented. Unlike the DOM parser, The SAX Parser parses files in order and does not save their content, the Dom parser first parses the XML file and stores it in an object tree. It can be seen that the DOM mode consumes more memory resources. Before parsing XML, you must first create an saxparser instance,
Saxparserfactory factory = saxparserfactory. newinstance ();
Saxparser = factory. newsaxparser ();
Next we need to get the input stream of the XML file and pass it as a parameter to the parse method of saxparser,
Inputstream is = This. getclass (). getresourceasstream ("phone. xml ");
Saxparser. parse (is, new basichandler (this ));
So how does saxparser Parse XML files? Defaulthandler is the default event processor base class of sax2. The method for processing XML parsing events is as follows:
Startdocument ()
Startelement (Java. Lang. String Uri, java. Lang. String localname, java. Lang. String QNAME, attributes)
Characters (char [] CH, int start, int length)
Endelement (Java. Lang. String Uri, java. Lang. String localname, java. Lang. String QNAME)
Enddocument ()
By default, the above method of defaulthandler does not do anything. Therefore, we must expand defaulthandler and overwrite the above method. Our program provides a basichandler to process XML files.
Class basichandler extends defaulthandler
There are two member variables in the basichandler class.
Private vector phones = new vector ();
Private stack tagstack = new stack ();
Phones is used to store the parsed phone objects, while tagstack is used to store the names of the parsed elements, such as sonyericsson, phone, name, and color. After the document is explained, the resolution result is displayed on the mobile phone screen in the enddocument () method. In order to give readers a clearer understanding of the parsing sequence of the sax Parser, here I use some print statements to print out important information. The following are some important methods for basichandler:
Package example; </P> <p> Import Java. util. vector; <br/> Import Java. util. stack; <br/> Import Org. XML. sax. helpers. defaulthandler; <br/> Import Org. XML. sax. saxexception; <br/> Import Org. XML. sax. attributes; </P> <p> public class basichandler <br/> extends defaulthandler {<br/> private vector phones = new vector (); <br/> private stack tagstack = new stack (); <br/> Public basichandler () {<br/>}</P> <p> Public void startdocument () throws saxexception {<br/> system. out. println ("startdocument"); <br/>}</P> <p> Public void startelement (string Uri, string localname, <br/> string QNAME, attributes) throws <br/> saxexception {<br/> system. out. println ("The QNAME is" + QNAME); <br/> If (QNAME. equals ("phone") {<br/> phone = new phone (); <br/> phones. addelement (phone); <br/>}< br/> tagstack. push (QNAME); <br/> system. out. println ("the tag stacks length is" + tagstack. size (); <br/>}</P> <p> Public void characters (char [] CH, int start, int length) throws saxexception {<br/> string chars = new string (CH, start, length ). trim (); <br/> system. out. println ("the character is" + chars); <br/> If (chars. length ()> 0) {<br/> string QNAME = (string) tagstack. peek (); <br/> phone currentphone = (phone) phones. lastelement (); <br/> If (QNAME. equals ("name") {<br/> currentphone. setname (chars); <br/>}< br/> else if (QNAME. equals ("color") {<br/> currentphone. setcolour (chars); <br/>}</P> <p> Public void endelement (string Uri, string localname, string QNAME) throws <br/> saxexception {<br/> system. out. println ("the end QNAME is" + QNAME); <br/> tagstack. pop (); <br/>}</P> <p> Public void enddocument () throws saxexception {<br/> stringbuffer result = new stringbuffer (); <br/> for (INT I = 0; I <phones. size (); I ++) {</P> <p> phone currentphone = (phone) phones. elementat (I); </P> <p> result. append (currentphone. getname () + "yes" + currentphone. getcolour () + <br/> ""); <br/>}< br/> system. out. println (result. tostring (); <br/>}< br/>

 

Note:

 

JAXP --- characters (char [] CH, int start, int length)

 

XML file to be parsed

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

<? XML version = "1.0" encoding = "UTF-8"?>
<Sax> </sax>

The content between the sax labels is empty.

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

Public void characters (char [] CH, int start, int length)
Throws saxexception {

System. Out. println ("Run .....");
System. Out. Print (new string (CH, start, length ));
}

Characters method not executed

======================================

<Sax> </sax>

The content of the sax tag is an empty string.

Characters method execution

Result: run .....

==============================

<Sax>
<Name> 123 </Name>
</Sax>

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

When <sax> is parsed,

A "Carriage Return" located between the sax and name labels"

Characters is executed and the output is run...

When "123" is encountered, "Run... 123" is output"

The carriage return between </Name> and </sax> outputs "Run ....."

==================================

Result

Run .....

Run ....... 123

Run ......

======================================

Conclusion: <> </> Any "Carriage Return" "space character" or other "not blank" characters are displayed.

Will trigger the characters method

Phone. XML code:

<Phone> <br/> <Name> iphone4 </Name> <br/> <color> write </color> <br/> </phone> <br/>

 

MIDlet code:

Package example; </P> <p> Import javax. microedition. MIDlet. MIDlet; <br/> Import javax. XML. parsers. saxparserfactory; <br/> Import javax. XML. parsers. saxparser; <br/> Import Org. XML. sax. *; <br/> Import javax. XML. parsers. *; <br/> Import Java. io. inputstream; <br/> Import Java. io. *; </P> <p> public class saxparsexml extends MIDlet {<br/> Public saxparsexml () {<br/>}</P> <p>/** <br/> * destroyapp <br/> * @ Param boolean0 Boolean <br/> */<br/> protected void destroyapp (Boolean boolean0) {<br/>}</P> <p>/** <br/> * Startapp <br/> */<br/> protected void Startapp () {<br/> saxparserfactory factory = saxparserfactory. newinstance (); <br/> try {<br/> saxparser = factory. newsaxparser (); <br/> inputstream is = This. getclass (). getresourceasstream ("phone. XML "); <br/> try {<br/> saxparser. parse (is, new basichandler (); <br/>}< br/> catch (ioexception ex1) {<br/>}< br/> catch (saxexception ex1) {<br/>}< br/> catch (saxexception ex) {<br/>}< br/> catch (parserconfigurationexception ex) {<br/>}</P> <p>/** <br/> * pauseapp <br/> */<br/> protected void pauseapp () {<br/>}</P> <p >}< br/>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.