加入收藏 | 设为首页 | 会员中心 | 我要投稿 | RSS
您当前的位置:首页 > 阅读中心 > 软件学习

SAX解析XML

时间:2014-05-04 10:29:57  来源:JSP天空网  作者:未知
package simpleTest;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.Locator;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
import java.io.IOException;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

class TestSAX extends DefaultHandler
{
private StringBuffer buf;

public TestSAX()
{
super();
}
public void setDocumentLocator(Locator locator)
{
}
public void startDocument() throws SAXException
{
buf=new StringBuffer();
System.out.println("*******开始解析文档*******");
}
public void endDocument() throws SAXException
{
System.out.println("*******文档解析结束*******");
}

public void startPrefixMapping( String prefix, String uri )
{
System.out.println(" 前缀映射: " + prefix +" 开始!"+ " 它的URI是:" + uri);
}

public void endPrefixMapping( String prefix )
{
System.out.println(" 前缀映射: "+prefix+" 结束!");
}
public void processingInstruction( String target, String instruction )
throws SAXException
{
}
public void ignorableWhitespace( char[] chars, int start, int length ) throws SAXException
{
}

public void skippedEntity( String name ) throws SAXException
{
}

public void startElement(String namespaceURI,String localName,String qName,Attributes atts)
{
System.out.println("*******开始解析元素*******");
System.out.println("元素名"+qName);
for(int i=0;i<atts.getLength();i++)
{
System.out.println("元素名"+atts.getLocalName(i)+"属性值"+atts.getValue(i));
}
}

public void endElement(String namespaceURI,String localName,String fullName )throws SAXException
{
System.out.println("******元素解析结束********");
}
public void characters( char[] chars, int start, int length )throws SAXException
{
//将元素内容累加到StringBuffer中
buf.append(chars,start,length);
}

public static void main(String args[])
{
try{

SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sp = sf.newSAXParser();
TestSAX testsax=new TestSAX();
sp.parse(new InputSource("D:testsimpleTestclassessimpleTesttest.xml"),testsax);

}catch(IOException e)
{
e.printStackTrace();
}catch(SAXException e)
{
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}



}
}
XML文件如下:
<?xml version="1.0" encoding="gb2312"?>
<row>
<person>
<name>王小明</name>
<college>信息学院</college>
<telephone>6258113</telephone>
<notes>男,1955年生,博士,95年调入海南大学</notes>
</person>
</row> 
来顶一下
返回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
推荐资讯
后牧工业区厂房1500平出租
后牧工业区厂房1500平
现实的童话公主艾米·罗森
现实的童话公主艾米·
科比专为大场面而生
科比专为大场面而生
“最美清洁工”原是《赤壁》宫女
“最美清洁工”原是《
相关文章
    无相关信息
栏目更新
栏目热门