myhandler.java

来自「java2 primer plus一书源程序」· Java 代码 · 共 109 行

JAVA
109
字号
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;

public class MyHandler extends DefaultHandler
{
    private SAXBooks books; 
    private boolean readingAuthor;
    private boolean readingTitle;
    private boolean readingPrice;

    public SAXBooks getBooks()
    {
        return this.books;
    }

    public void startElement( String uri,
                              String localName,
                              String qName,
                              Attributes attributes )
    {
        System.out.println( "Found element: " + qName );
        if( qName.equalsIgnoreCase( "books" ) )
        {
            books = new SAXBooks();
        }
        else if( qName.equalsIgnoreCase( "book" ) )
        {
            SAXBook book = new SAXBook();
            for( int i=0; i<attributes.getLength(); i++ )
            {
                if( attributes.getQName( i ).equalsIgnoreCase( "category" ) )
                {
                     book.setCategory( attributes.getValue( i ) );
                }
            }
            books.addBook( book );
        }
        else if( qName.equalsIgnoreCase( "author" ) )
        {
            this.readingAuthor = true;
        }
        else if( qName.equalsIgnoreCase( "title" ) )
        {
            this.readingTitle = true;
        }
        else if( qName.equalsIgnoreCase( "price" ) )
        {
            this.readingPrice = true;
        }
        else
        {
            System.out.println( "Unknown element: " + qName );
        }
    }

    public void startDocument() 
    {
        System.out.println( "Starting..." );
    }

    public void endDocument() 
    {
        System.out.println( "Done..." );
    }
    
    public void characters( char[] ch,
                            int start,
                            int length )
    {
	String chars = new String( ch, start, length).trim();
        if( chars.length() == 0 )
        {
            return;
        }

        SAXBook book = books.getLastBook();
        if( readingAuthor )
        {
            book.setAuthor( chars ); 
        }
        else if( readingTitle )
        {
            book.setTitle( chars ); 
        }
        else if( readingPrice )
        {
            book.setPrice( Float.parseFloat( chars ) );
        }
    }
                
    public void endElement( String uri,
                            String localName,
                            String qName )
    {
        System.out.println( "End Element: " + qName );
        if( qName.equalsIgnoreCase( "author" ) )
        {
            this.readingAuthor = false;
        }
        else if( qName.equalsIgnoreCase( "title" ) )
        {
            this.readingTitle = false;
        }
        else if( qName.equalsIgnoreCase( "price" ) )
        {
            this.readingPrice = false;
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?