WEB开发网
开发学院WEB开发Jsp [JAVA100例]069、使用SAX解析XML 阅读

[JAVA100例]069、使用SAX解析XML

 2008-01-05 09:28:29 来源:WEB开发网   
核心提示:ReadxmlDemo.javaimport java.io.*;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.*;public class ReadXmlDemo extends DefaultHandler {

ReadxmlDemo.java


import java.io.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;


public class ReadXmlDemo extends DefaultHandler {


   public static void main(String[] arguments) {
     if (arguments.length > 0){
   ReadXmlDemo read = new ReadXmlDemo(arguments[0]);
 } else {
   System.out.PRintln("Usage: java ReadXmlDemo filename");
 }
   }


   ReadXmlDemo(String xmlFile) {
     File input = new File(xmlFile);
 SAXParserFactory factory = SAXParserFactory.newInstance();
 factory.setValidating(true);
 try {
   SAXParser sax = factory.newSAXParser();
   sax.parse(input, new XmlHandler() );
 } catch (ParserConfigurationException pce) {
   System.out.println("Could not create that parser.");
   System.out.println(pce.getMessage());
 } catch (SAXException saxe) {
   System.out.println("Problem with the SAX parser.");
   System.out.println(saxe.getMessage());
 } catch (IOException ioe) {
   System.out.println("Error reading file.");
   System.out.println(ioe.getMessage());
 }
   }
}


class XmlHandler extends DefaultHandler {
   static int READING_NAME = 1;
   static int READING_SEX = 2;
   static int READING_BIRTH = 3;
   static int READING_NOTHING = 0;
   int currentActivity = READING_NOTHING;
   ReadXml xml = new ReadXml();


   XmlHandler() {
     super();
   }


   public void startElement(String uri, String localName, String qName, Attributes attributes) {
  
     if (qName.equals("title"))
       currentActivity = READING_NAME;
 else if (qName.equals("file"))
   currentActivity = READING_SEX;
 //else if (qName.equals("Birth"))
   //currentActivity = READING_BIRTH;
   }


   public void characters(char[] ch, int start, int length) {
     String value = new String(ch, start, length);
 if (currentActivity == READING_NAME)
   xml.name = value;
 if (currentActivity == READING_SEX)
   xml.sex = value;
 //if (currentActivity == READING_BIRTH)
   //xml.birth = value;
   }



Tags:JAVA 使用 SAX

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接