Analyze XML in J2ME development

xiaoxiao2021-03-06  88

At present, XML has been widely used in the field of data exchange, XML is based on plain text, with excellent cross-platform characteristics. This article will tell how to resolve XML in J2ME for data transmission.

XML is relatively simple, and it is very convenient to read. However, the XML parser must be communicated normally in the client and the server, and the XML support is not provided in MIDP 1.0 due to the lack of memory information in the initial mobile information devices and the processor. With the improvement of memory and processors, the support of XML is possible. The XML parser is provided in JSR182, but this is not the API in the standard MIDP to require specific implementation to support. Fortunately, there is a third-party API to provide support for parsing XML, which is more known as KXML and Nanoxml.

Before using XML, you must consider whether you must use it to transfer data, because parsing XML is more cost-effective, especially under the conditions of CPU and memory resources. If we can use DataInputStream and DataOutputStream transfer, try not to use XML. There are two kinds of parsers of XML, one is confirmation, and he verifies the validity of XML documents before parsing, ensuring that this is required. The other is non-confirmation, and he does not perform verification work directly, which will undoubtedly this speed will be fast. KXML and Nanoxml are such parsers. They also have differences, KXML is a more resolution of incremental parsers, which is relatively efficient when parsing large documents. Nanoxml is a step parser. This will undoubtedly spess a lot of memory if the document is large. To use KXML you can download from http://www.kxml.org, at http://nanoxml.sourceforge.net You can download Nanoxml.

To use KXML, you must first get an XMLParser instance, which uses reader as the parameters of the constructor: try {reader r = .....; xmlparser Parser = New XMLParser (r);} catch (java.ioException E ) {// Handle Exception ....

If your xml document stored in a String, then you can use ByteArrayInputStream and InputStreamReader: String xml = " some xml "; ByteArrayInputStream bin = new ByteArrayInputStream (xml.getBytes ()); XmlParser parser = new XmlParser (new InputStreamReader (bin)); when data is received from the internet may be so: HttpConnection conn = .....; InputStreamReader doc = new InputStreamReader (conn.openInputStream ()); XmlParser parser = new XmlParser (doc); to give After the Parser instance, we can call the Read method for parsing. The Read method returns a parseelent, and we can resolve XML by judging his type. Try {Boolean KeepParsing = true; while (KeEpparsing) {Parseevent Event = PARSER.READ (); Switch (Event.getType ()) {CASE XML.Start_tag: .....//dle start of an xml tag break; Case Xml.end_Tag: .....// Handle End of an XML Tag Break; Case Xml.Text: .....//dle text within a tag break; case xml.Whitespace: ..... / / Handle Whitespace Break; Case Xml.comment: ...../ Handle Comment Break; Case Xml.Processing_instruction: ...../ Handle XML Pi Break; Case Xml.DOCTYPE: ..... / Handle XML DOCTYPE BREAK; CASE XML.END_Document: ..... // end of document; keEpparsing = false; break;}}} catch (java.io}} catch (java.io}} catch Tion E) {}

If you want to use Nanoxml, you first have to create a KXMLELEMENT instance and then call ParseFromReader, Parsestring or Parsechararray. Since he is a step parser, it will generate an Object Tree after analyzing the entire document. Each node is an instance of kxmlelement, which can be navigated on this tree by calling getChildren. HttpConnection conn = .....; InputStreamReader doc = new InputStreamReader (conn.openInputStream ()); kXMLElement root = new kXMLElement (); try {root.parseFromReader (doc);} catch (kXMLParseException pe) {} catch (IOException IE) {}

Below is a J2ME application simple demonstration how to resolve XML. If there is time, you can write a complex test program. You can download source code from the following address: XMLTest. Inside the source code of KXML and Nanoxml, please refer to their official website if you want to get the latest source code, provide KXML online apipackage com.ericgiguere.techtips at this site.

Import java.ior. *; import java.UTIL. *; import javax.microedition.lcdui. *; import javax.microedition.midlet. *; import nanoxml. *; import org.kxml. *; import org.kxml.parser . *;

/ ** * Simple MIDlet That DemonStrates How AN XML Document Can Be * Parsed Using KXML or Nanoxml. * /

Public class xmltest extends MIDlet {

// Our XML Document - Normal Static String XmlDocument = " Apple " " Orange " " pear "; private Display display; private Command exitCommand = new Command (" Exit ", Command.EXIT, 1); public XMLTest () {} protected void destroyApp (boolean unconditional) throws MIDletStateChangeException { exitMIDlet ();} protected void pauseApp () {} protected void startApp () throws MIDletStateChangeException {if (display == null) {// first time called ... initMIDlet ();}} private void initMIDlet () {display = Display.getdisplay (this); string [] items; // items = parseusingnanoxml (xmldocument); items = parse UsingkXML (xmlDocument); display.setCurrent (new ItemList (items));} public void exitMIDlet () {notifyDestroyed ();} // Parses a document using NanoXML, looking for // "item" nodes and returning their content as an . // array of strings private String [] parseUsingNanoXML (String xml) {kXMLElement root = new kXMLElement (); try {root.parseString (xml); Vector list = root.getChildren (); Vector items = new Vector (); For (int i = 0; i

i) {kxmlelement node = (kxmlelement) list.elementat (i); string tag = node.gettagname (); if (tag == null) Continue; if (! tag.equals ("item")) Continue; items. Adde.getContents ();} String [] TMP = new string [items.size ()]; items.copyinto (tmp); return tmp;} catch (kxmlparseException ke) {return new string [] {ke. toString ()};}} // Parses a document using kXML, looking for "item" // nodes and returning their content as an // array of strings private String [] parseUsingkXML (String xml) {try {ByteArrayInputStream bin =. New byteArrayInputStream (Xml.getBytes ()); InputStreamReader in = New InputStreamReader (BIN); XMLPAR Ser Parser = new xmlparser (in); vector items = new vector (); parsekxmlitems (Parser, items); string [] TMP = new string [items.size ()]; items.copyinto (tmp); return tmp;} catch (IOException e) {return new String [] {e.toString ()};}} private void parsekXMLItems (XmlParser parser, Vector items) throws IOException {boolean inItem = false; while (true) {ParseEvent event = parser.read ();

转载请注明原文地址:https://www.9cbs.com/read-122508.html

New Post(0)