这个例子展示了如何用SAX接口来解析XML文档
下面是我要解析的文档emp.xml
<?xml version="1.0"?>
<employs>
<employ>
<name>aaa</name>
<age>33</age>
<sex>m</sex>
<tel>88881234</tel>
<img>1.jpg</img>
</employ>
<employ>
<name>bbb</name>
<age>35</age>
<sex>m</sex>
<tel>88882345</tel>
<img>2.jpg</img>
</employ>
<employ>
<name>ccc</name>
<age>24</age>
<sex>f</sex>
<tel>888845657</tel>
<img>3.jpg</img>
</employ>
<employs>
我使用的开发环境是Jbuilder5,下面就是java程序
import java.io.IOException;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.apache.xerces.parsers.SAXParser;
import java.util.Stack;
public class XmlToHtml extends DefaultHandler {
String strName;
String strAge;
String strSex;
String strTel;
String strImage;
private Stack stackName=new Stack();
private Stack stackAge=new Stack();
private Stack stackSex=new Stack();
private Stack stackTel=new Stack();
private Stack stackImage=new Stack();
private int flag;
public static void main(String[] argv) {
if (argv.length != 1) {
System.out.println("Usage: java XmlToHtml [URI]");
System.exit(0);
}
String uri = argv[0];
try {
XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
XmlToHtml XmlToHtmlInstance = new XmlToHtml();
parser.setContentHandler(XmlToHtmlInstance);
parser.parse(uri);
}
catch(IOException ioe) {
ioe.printStackTrace();
}
catch(SAXException saxe) {
saxe.printStackTrace();
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
String s = new String(ch, start, length);
if (ch[0] == '\n')
return;
if(flag==1)
{stackName.push(s);}
else if(flag==2)
{stackAge.push(s);}
else if(flag==3)
{stackSex.push(s);}
else if(flag==4)
{stackTel.push(s);}
else if(flag==5)
{stackImage.push(s);}
}
public void endDocument() throws SAXException {
for (int count=stackName.size()-1;count>=0;count--){
String strName=stackName.elementAt(count).toString();
String strAge=stackAge.elementAt(count).toString();
String strSex=stackSex.elementAt(count).toString();
String strTel=stackTel.elementAt(count).toString();
String strImage=stackImage.elementAt(count).toString();
System.out.println(strName+" "+strAge+" "+strSex+" "+strTel+" "+strImage+"");
//输出解析后的数据
}
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if(localName.equals("name" ))
{flag=1;}
else if (localName.equals("age"))
{flag=2;}
else if(localName.equals("sex"))
{flag=3;}
else if(localName.equals("tel"))
{flag=4;}
else if(localName.equals("img"))
{flag=5;}
}
}
本文地址:http://com.8s8s.com/it/it18319.htm