Java XML 处理: SAX方式

SAX 方式处理的好处是:耗费内存很少,速度快;缺点是很多逻辑要自己处理。

 

典型代码:

这是一个处理XML格式的excel表格的代码。只保留了框架逻辑,删除了细节:

主要是对5个方法的重写:startDocument(); endDocument(); startElement(); endElement();

characters(char[] ch, int start, int length);


 

package …;

 

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;

public class XingGongInfoLoader extends DefaultHandler
{
    final static int MAX_COL = 16;
    final static int FirstRow = 1;
    final static int FirstCol = 1;
    final static String TAG_ROW = "Row";
    final static String TAG_COL= "Cell";
    final static String TAG_DATA = "Data";
    final static String ATTR_COL_IDX = "ss:Index";


    private int currentRow = 0;
    private int currentCol = 0;
    private String cellText;

    private StringBuffer textBuf = new StringBuffer();
    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        currentRow = FirstRow;//第一行从1开始
    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException
    {
        super.startElement(uri, localName, qName, attributes);
        //System.out.println("Element :"+localName + ","+ qName);//debug
        if (TAG_ROW.equalsIgnoreCase(qName)){
            currentCol = FirstCol -1;
        }else if (TAG_COL.equalsIgnoreCase(qName)){
            //确定这个cell所表示的列号
            if (attributes!=null){
                String lsIdx = attributes.getValue(ATTR_COL_IDX);
                if (lsIdx!=null)
                    try{
                        int col = Integer.parseInt(lsIdx);
                        //System.out.println("Specified col:"+col);
                        currentCol = col;
                    }catch(Exception ex){ //
                    }
                else{
                    currentCol++;
                    //System.out.println("auto increment col:"+currentCol);
                }
            }else{
                    currentCol++; //没有指定列号,自动+1
                    //System.out.println("auto increment col:"+currentCol);
            }
        }else if (TAG_DATA.equalsIgnoreCase(qName)){
            //列数据,在Character中处理
            textBuf.delete(0, textBuf.length());//先清空
        }
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        super.characters(ch, start, length);
        for (int i=0;i<length;i++)
            textBuf.append(ch[start + i]);
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        super.endElement(uri, localName, qName);
        if (TAG_ROW.equalsIgnoreCase(qName)){
            currentRow ++; //next row number
            …

        }else if (TAG_COL.equalsIgnoreCase(qName)){
            if (currentRow==FirstRow){
                //System.out.println("Parsing "+cellText);
                //第一行,处理表头
                xingInfoMap = new HashMap<XingYao,String[]>();
                if ("特性".equals(cellText)){
                    this.colStoreIdx[currentCol] = XingCharStoreIdx;
                    //System.out.println("特性 col="+currentCol);
                }else if ("命理".equals(cellText)){
                    this.colStoreIdx[currentCol] = XingMingLiStoreIdx;
                    //System.out.println("命理 col="+currentCol);
                }else{
                    …

                }
            }else{
                //数据行
                if (currentCol ==FirstCol){
                   //第一列,可能需要特殊处理

                }else{
                    //数据列
                    xingInfo[this.colStoreIdx[currentCol]] = cellText;
                

                }
            }
        }else if (TAG_DATA.equalsIgnoreCase(qName)){
                //列数据,在Character中处理
            cellText = textBuf.toString().trim();
            textBuf.delete(0,textBuf.length()); //清空,以备下一个
        }
    }

    public void load(InputStream xmlIs)
    {
        try
        {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            sp.parse(xmlIs,this);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    static public void main(String args[])
    {
        XingGongInfoLoader loader = new XingGongInfoLoader();
        InputStream xmlIs  = ClassLoader.getSystemResourceAsStream("res/data/XingGongInfo.xml");
        loader.load(xmlIs);
        String xInfo[] = loader.xingInfoMap.get(XingYao.七杀);
        for (GongType gt:GongType.values()){
            System.out.println("七杀在"+gt+":\n\t"+xInfo[gt.ordinal()]);
        }
    }

}

posted on 2012-05-21 11:28  nullpointer  阅读(209)  评论(0)    收藏  举报