xml之SAX解析

来源:互联网 发布:查找重复删除知乎 编辑:程序博客网 时间:2024/05/22 13:39
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


















}
0 0