XML 文件的操作(五)用sax解析xml 读取xml
- <?xml version="1.0" encoding="gb2312"?>
- <?xml-stylesheet type="text/xsl" href="students.xsl"?>
- <students>
- <student sn="01">
- <name>张三</name>
- <age>18</age>
- </student>
- <student sn="02">
- <name>李四</name>
- <age>20</age>
- </student>
- </students>
使用SAX读取XML文件:
- package com.ibm.xml;
- import java.io.File;
- import java.io.IOException;
- import javax.xml.parsers.ParserConfigurationException;
- import javax.xml.parsers.SAXParser;
- import javax.xml.parsers.SAXParserFactory;
- import org.xml.sax.Attributes;
- import org.xml.sax.SAXException;
- import org.xml.sax.helpers.DefaultHandler;
- /**
- * 使用SAX读取XML文件
- * @author Administrator
- *
- */
- public class SAXPrinter extends DefaultHandler {
- /**
- * 重新的方法
- */
- public void startDocument() throws SAXException
- {
- System.out.println("<?xml version=\"1.0\" encoding='gb2312'?>");
- }
- /**
- * 重新的方法
- */
- public void processingInstruction(String target, String data) throws SAXException
- {
- System.out.println("<?"+target+" "+data+"?>");
- }
- /**
- * 重新的方法
- */
- public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException
- {
- System.out.print("<"+qName);
- int len=attrs.getLength();
- for(int i=0;i<len;i++)
- {
- System.out.print(" ");
- System.out.print(attrs.getQName(i));
- System.out.print("=\"");
- System.out.print(attrs.getValue(i));
- System.out.print("\"");
- }
- System.out.print(">");
- }
- /**
- * 重新的方法
- */
- public void characters(char[] ch, int start, int length) throws SAXException
- {
- System.out.print(new String(ch,start,length));
- }
- /**
- * 重新的方法
- */
- public void endElement(String uri, String localName, String qName) throws SAXException
- {
- System.out.print("</"+qName+">");
- }
- public static void main(String arge[]){
- SAXParserFactory spf=SAXParserFactory.newInstance();
- try
- {
- SAXParser sp=spf.newSAXParser();
- sp.parse(new File("students.xml"),new SAXPrinter());
- }
- catch (ParserConfigurationException e)
- {
- e.printStackTrace();
- }
- catch (SAXException e)
- {
- e.printStackTrace();
- }
- catch (IOException e)
- {
- // TODO 自动生成 catch 块
- e.printStackTrace();
- }
- }
- }

浙公网安备 33010602011771号