|
Introducing XML parsing in J2ME devices |
|
|
javax.xml.parsers package defines the api for XML parsing.JSR 172 implements
Java API for XML parsing. This API represents SAX parser.
Illustration below parse an XML file.
import java.io.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.io.file.*;
import javax.microedition.lcdui.*;
public class XMLMidlet extends MIDlet
{
public XMLMidlet() {}
protected void startApp()
{
try
{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
FileConnection fc = (FileConnection) Connector.open(
"file:///root1/helloworld.xml");
InputStream is = fc.openInputStream();
InputSource inputSource = new InputSource(is);
saxParser.parse(is,new xmlHandler(this));
}
catch(Exception ex) {}
}
protected void alert(String msg)
{
Display display = Display.getDisplay(this);
Form form = new Form("HelloWorld XML !");
form.append(msg);
display.setCurrent(form);
}
protected void pauseApp() {}
protected void destroyApp(boolean bool) {}
}
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
import java.util.*;
class xmlHandler extends DefaultHandler
{
private XMLMidlet midlet;
private Vector nodes = new Vector();
private Stack tagStack = new Stack();
public xmlHandler (XMLMidlet midlet)
{
this.midlet = midlet;
}
public void startDocument() throws SAXException {}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if(qName.equals("node1"))
{
Noden node = new Noden();
nodes.addElement(node);
}
tagStack.push(qName);
}
public void characters(char[] ch, int start, int length) throws SAXException
{
String chars = new String(ch, start, length).trim();
if(chars.length() > 0)
{
String qName = (String)tagStack.peek();
Noden currentnode = (Noden)nodes.lastElement();
if (qName.equals("name"))
{
currentnode.setName(chars);
}
else if(qName.equals("type"))
{
currentnode.setType(chars);
}
}
}
public void endElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
tagStack.pop();
}
public void endDocument() throws SAXException
{
StringBuffer result = new StringBuffer();
for (int i=0; i<nodes.size(); i++)
{
Noden currentnode = (Noden)nodes.elementAt(i);
result.append("Name : "currentnode.getName() + " Type : " +
currentnode.getType() + "\n");
}
midlet.alert(result.toString());
}
class Noden
{
private String name;
private String type;
public Noden()
{}
public void setName(String name)
{
this.name = name;
}
public void setType(String type)
{
this.type = type;
}
public String getName()
{
return name;
}
public String getType()
{
return type;
}
};
}
|
You can also use NanoXML which is a small XML parser for Java.
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.