태그 'sax'에 해당하는 글 1건

=============== saxParser.java ========
package sax;

import java.io.IOException;

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

import org.xml.sax.helpers.*;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class SaxParser1 {
 private void init() throws ParserConfigurationException, SAXException, IOException{
  SAXParserFactory factory = SAXParserFactory .newInstance();
  factory.setValidating(true);
  SAXParser parser = factory.newSAXParser(); 
  parser.parse("./src/books.xml", new MyDefaultHandler());
 }
 
 public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException{
  SaxParser1 sax = new SaxParser1();
  sax.init();
 }
 
 class MyDefaultHandler extends DefaultHandler{
  public void startDocument() throws SAXException{
   System.out.println("처음");  
  }
 
  public void startElement(String  uri,
                String  localName,
                String  qName,
                Attributes  attributes)
         throws SAXException {  
   System.out.println("<"+qName+">");
   for(int i = 0 ; i < attributes.getLength();i++){
    System.out.println("속성 : "+ attributes.getQName(i)+":"+attributes.getValue(i));
   }
  }
 
  public void characters(char[] ch,
                int start,
                int length)
         throws SAXException{
   System.out.println("내용 : "+new String(ch,start,length)+"");
  }
 
  public void error(SAXParseException  e)
        throws SAXException {
   System.out.println(e);
  }
 
 
 }
}
==============================================

- sax 유형별로 검색하기

====================== FindBook.java =============
package sax;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import javax.xml.parsers.*;

public class FindBook {
    ///Field
    ///Constructor
    ///Method
    public static void main(String args[]) {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
          
            System.out.println("1. ISBN 으로 검색");
            System.out.println("2. Title로 검색");
            System.out.println("3. Author로 검색");
            System.out.print("=>");
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            int inputNum = Integer.parseInt(br.readLine());
            FindBookEventHandler handler;
            switch(inputNum){
             case 1:
              System.out.println("########################################");
                 System.out.println("ISBN으로 검색");
                 System.out.println("########################################");
                 handler = new FindBookEventHandler("ISBN", "asd");
                 parser.parse("src/books.xml", handler);
                 break;
               
             case 2:
              System.out.println("########################################");
                 System.out.println("Title로 검색");
                 System.out.println("########################################");
                 handler = new FindBookEventHandler("Title", "제목213");
                 parser.parse("src/books.xml", handler);
                 break;
               
             case 3:
              System.out.println("########################################");
                 System.out.println("Author로 검색");
                 System.out.println("########################################");
                 handler = new FindBookEventHandler("Author", "김씨");
                 parser.parse("src/books.xml", handler);
                 break;
             default:
              System.out.println("잘못입력하였습니다");           
            }
          
          
        } catch(Exception e) {
         System.out.println("잘못입력하였습니다");
            e.printStackTrace();
        }
    }
}
------------------------- FindBookEventHandler.java -----------------
package sax;

import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.util.*;

public class FindBookEventHandler extends DefaultHandler {
    ///Field
    private boolean isBook, isTitle, isAuthor, isPrice;
    private String condition, keyWord;
    private Hashtable hash;
    private Attributes attributes;

    ///Constructor
    public FindBookEventHandler(String condition, String keyWord) {
        //검색 엘리먼트
     this.condition = condition;
        //검색 문자열
     this.keyWord = keyWord;
     //검색 내용을 저장할 Hashtable 객체
        this.hash = new Hashtable();
    }

    ///Method
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
     if(qName.equals("book")) {
            isBook = true;
            String isbn = attributes.getValue("ISBN");
            hash.put("ISBN", isbn);
        } else if(qName.equals("Title")) {
            isTitle = true;
        } else if(qName.equals("Author")) {
            isAuthor = true;
        } else if(qName.equals("FixedPrice")) {
            isPrice = true;
        }
    }
    public void characters(char[] ch, int start, int length) throws SAXException {
        String str = new String(ch,start,length).trim();
        if(isTitle) {
            hash.put("Title", str);
            isTitle = false;
        } else if(isAuthor) {
            hash.put("Author", str);
            isAuthor = false;
        } else if(isPrice) {
            hash.put("FixedPrice", str);
            isPrice = false;
        }
    }
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if(qName.equals("book")) {
         if(condition.equals("ISBN")) {
                String isbn = (String) hash.get("ISBN");
                if(isbn.indexOf(keyWord)!=-1) displayBookInfo();
         } else if(condition.equals("Title")) {
                String title = (String) hash.get("Title");
                if(title.indexOf(keyWord)!=-1) displayBookInfo();
            } else if(condition.equals("Author")) {
                String author = (String) hash.get("Author");
                if(author.indexOf(keyWord)!=-1) displayBookInfo();
            }
            hash.clear();
            isBook = false;
        }
    }
    public void displayBookInfo() {
        System.out.println("Title: " + (String) hash.get("Title"));
        System.out.println("Author: " + (String) hash.get("Author"));
        System.out.println("Price: " + (String) hash.get("FixedPrice"));
        System.out.println("----------------------");      
    }
 public void warning(SAXParseException exception) throws SAXException {
  throw new SAXException("warning 이벤트 처리");
 }
 public void error(SAXParseException exception) throws SAXException {
  System.out.println("DTD 또는 XML Schema 문서 구조에 위배됩니다.");
  System.out.println("유효하지 않는 문서 입니다.");   
  throw new SAXException("error 이벤트 처리");
 }
 public void fatalError(SAXParseException exception) throws SAXException {
  System.out.println("XML 권고안의 내용을 지키지 않았습니다.");
  System.out.println("잘 짜여진 XML 문서가 아닙니다.");
  throw new SAXException("fatalError 이벤트 처리");
 }   
}
xml, sax