⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 july01_ericg.txt

📁 TechTips j2me的常用技巧. 网络功能
💻 TXT
📖 第 1 页 / 共 2 页
字号:
                break;
        }
    }
}
catch( java.io.IOException e ){
}

The ParseEvent class defines a number of methods for returning 
information about an element. The getType method, for example, 
returns the element type, such as whether it's the start of 
a tag, a comment, and so on. Other methods provide additional
information, such as the text within a tag or the attributes of
a tag. The parsing stops when the END_DOCUMENT event is reached.

kXML makes it fairly easy to do recursive-descent style parsing 
of a document, where the state of the parsing is implicitly 
maintained by calling methods recursively in response to a new
parsing event. In simple cases you can do this just by keeping 
track of the last tag you saw.

To use NanoXML, you must also download some source code. The 
official NanoXML web site is http://nanoxml.sourceforge.net.  
A modified version of NanoXML that is compatible with the CLDC
(the original NanoXML is for J2SE-based
systems) is found at http://www.ericgiguere.com/nanoxml. As with 
kXML, you must include the source for NanoXML with your 
application. You then add the following import statement to your 
application:

import nanoxml.*;

To parse a document, create an instance of the kXMLElement class, 
and invoke one of parseFromReader, parseString, or 
parseCharArray:

HttpConnection    conn = .....;
InputStreamReader doc = 
         new InputStreamReader( conn.openInputStream() );
kXMLElement       root = new kXMLElement();

try {
    root.parseFromReader( doc );
}
catch( kXMLParseException pe ){
}
catch( IOException ie ){
}

Since NanoXML is a single-step parser, this parses the entire 
document and transforms it into a tree of XML elements. The root 
of the tree is the instance of kXMLElement that you created, and
each node of the tree is another instance of kXMLElement. You can
us methods such as getChildren, getTagName, and getContents to 
navigate through the document tree.

To demonstrate how parsing can be done, here is an MIDP 
application that fills a List component with a set of strings.
The application uses kXML. To parse with NanoXML, uncomment the 
line that calls parseUsingNanoXML, and comment the line that calls 
parseUsingkXML. A complete project is also available for this
application at http://www.ericgiguere.com/techtips/XMLTest.zip
You can run this project using the J2ME Wireless Toolkit.

package com.ericgiguere.techtips;

import java.io.*;
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 -- normally this would be something you
    // download.
    
    private static String xmlDocument =
        "<list><item>apple</item>" +
              "<item>orange</item>" +
              "<item>pear</item></list>";
              
    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 = parseUsingkXML( 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 < list.size(); ++i ){
                kXMLElement node = 
                     (kXMLElement) list.elementAt( i );
                String      tag = node.getTagName();
                
                if( tag == null ) continue;
                if( !tag.equals( "item" ) ) continue;
                
                items.addElement( node.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 );
            XmlParser 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();
            switch( event.getType() ){
                case Xml.START_TAG:
                    if( event.getName().equals( "item" ) ){
                        inItem = true;
                    }
                    break;
                case Xml.END_TAG:
                    if( event.getName().equals( "item" ) ){
                        inItem = false;
                    }
                    break;
                case Xml.TEXT:
                    if( inItem ){
                        items.addElement( event.getText() );
                    }
                    break;
                case Xml.END_DOCUMENT:
                    return;
            }
        }
    }
    
    // Simple List UI component for displaying the list of
    // items parsed from the XML document.
    
    class ItemList extends List implements CommandListener {
    
        ItemList( String[] list ){
            super( "Items", IMPLICIT, list, null );
            addCommand( exitCommand );
            setCommandListener( this );
        }
        
        public void commandAction( Command c, Displayable d ){
            if( c == exitCommand ){
                exitMIDlet();
            } 
        }
    }
}



.  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .

- NOTE

Sun respects your online time and privacy. The Java Developer 
Connection mailing lists are used for internal Sun 
Microsystems(tm) purposes only. You have received this email 
because you elected to subscribe. To unsubscribe, go to the 
Subscriptions page (http://developer.java.sun.com/subscription/), 
uncheck the appropriate checkbox, and click the Update button.

As of May  22, 2001, Sun Microsystems updated its Privacy Policy 
(http://sun.com/privacy) to give you a better understanding of 
Sun's Privacy Policy and Practice. If you have any questions, 
contact privacy@sun.com.

- SUBSCRIBE

To subscribe to a JDC newsletter mailing list, go to the 
Subscriptions page (http://developer.java.sun.com/subscription/), 
choose the newsletters you want to subscribe to, and click Update.


- FEEDBACK
Comments? Send your feedback on the J2ME Tech Tips to:

jdc-webmaster@sun.com


- ARCHIVES
You'll find the J2ME Tech Tips archives at:

http://java.sun.com/jdc/J2METechTips/index.html

- COPYRIGHT
Copyright 2001 Sun Microsystems, Inc. All rights reserved.
901 San Antonio Road, Palo Alto, California 94303 USA.

This document is protected by copyright. For more information, 
see:

http://java.sun.com/jdc/copyright.html


- LINKS TO NON-SUN SITES
The J2ME Tech Tips may provide, or third parties may provide, 
links to other Internet sites or resources. Because Sun has no 
control over such sites and resources, You acknowledge and 
agree that Sun is not responsible for the availability of such 
external sites or resources, and does not endorse and is not 
responsible or liable for any Content, advertising, products, 
or other materials on or available from such sites or resources. 
Sun will not be responsible or liable, directly or indirectly, 
for any damage or loss caused or alleged to be caused by or in 
connection with use of or reliance on any such Content, goods or 
services available on or through any such site or resource.

J2ME Tech Tips 
July 25, 2001

Sun, Sun Microsystems, Java, Java Developer Connection, and 
J2ME, J2SE and are trademarks or registered trademarks of 
Sun Microsystems, Inc. in the United States and other countries.




⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -