xml之SAX解析

package xml2;


import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


public class SaxHandler extends DefaultHandler
{
public void characters(char[] a,int b,int c) throws SAXException
{
String content=new String(a,b,c);
System.out.println("1"+content+"1");
super.characters(a, b, c);
}
public void endDocument() throws SAXException
{
System.out.println("end document");
super.endDocument();
}
public void endElement(String a,String b,String c) throws SAXException
{
System.out.println("end element:"+c);
super.endElement(a, b, c);
}
public void startDocument() throws SAXException
{
System.out.println("start document");
super.startDocument();
}
public void startElement(String a,String b,String c,Attributes d) throws SAXException
{
System.out.println("start element:"+c);
// super.startElement(uri, localName, qName, attributes);
if(d!=null)
{
for(int i=0;i<d.getLength();i++)
{
System.out.print(d.getQName(i) + "=\"" + d.getValue(i) + "\""); 
}
}
System.out.println(c+":");
super.startElement(a, b, c, d);

}

main.java

       SAXParserFactory f=SAXParserFactory.newInstance();
SAXParser parser=f.newSAXParser();
File ff=new File("e:/grade2.xml");
SaxHandler s=new SaxHandler();
parser.parse(ff, s);

xml 文档

<?xml version="1.0" encoding="UTF-8"?>  
<books>  
   <book id="001">  
      <title>Harry Potter</title>  
      <author>J K. Rowling</author>  
   </book>  
   <book id="002">  
      <title>Learning XML</title>  
      <author>Erik T. Ray</author>  
   </book>  
</books> 

输出结果:

start document
start element:books
books:
1  
   1
start element:book
id="001"book:
1  
      1
start element:title
title:
1Harry Potter1
end element:title
1  
      1
start element:author
author:
1J K. Rowling1
end element:author
1  
   1
end element:book
1  
   1
start element:book
id="002"book:
1  
      1
start element:title
title:
1Learning XML1
end element:title
1  
      1
start element:author
author:
1Erik T. Ray1
end element:author
1  
   1
end element:book
1  
1
end element:books
end document


















}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值