JSR 172实现了Java API来进行XML解析.
下边代码说明了如何解析一个XML文件
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;
}
};
}
本文介绍了一个使用JSR172规范中的Java API进行XML文件解析的例子。通过继承DefaultHandler类并实现特定的方法,可以处理XML文档中的元素、属性及文本内容。示例代码展示了如何初始化SAXParser并解析指定的XML文件。
3285

被折叠的 条评论
为什么被折叠?



