tw.com.javaworld.CH17.MyHandler (Java2HTML)

| MyHandler.java |

    1 package tw.com.javaworld.CH17;
    2
    3 import java.io.*;
    4 import java.util.*;
    5 import javax.xml.parsers.*;
    6 import org.xml.sax.*;
    7 import org.xml.sax.helpers.*;
    8
    9 public class MyHandler extends DefaultHandler {
    10
    11    private StringBuffer textBuffer;
    12    private HashMap hm_TagData;
    13    private String tagName;
    14
    15    public MyHandler(HashMap hm_TagData) {
    16        this.hm_TagData = hm_TagData;
    17    }
    18
    19    //當SAX遇到xml字元時，會自動呼叫的方法
    20    public void characters(char[] ch, int start, int len) {
    21        String s = new String(ch, start, len);
    22        if (textBuffer == null) {
    23            textBuffer = new StringBuffer(s);
    24        } else {
    25            textBuffer.append(s);
    26        }
    27    }
    28    public void startElement(String namespaceURI, String localName, String qName, Attributes atts) {
    29
    30        // 判斷重複的屬性名稱
    31        int count = 1;
    32        echoText();
    33        if (atts != null) {
    34            for (int i = 0; i < atts.getLength(); i++) {
    35                // 屬性名稱
    36                String aName = atts.getLocalName(i);
    37                if ("".equals(aName))
    38                    aName = atts.getQName(i);
    39                while (hm_TagData.get(aName) != null) {
    40                    aName = aName + count;
    41                    count++;
    42                }
    43                hm_TagData.put(aName, atts.getValue(i));
    44            }
    45        }
    46    }
    47    public void endElement(String namespaceURI, String localName, String qName) {
    48        String eName = localName;
    49        // 標籤名稱
    50        if ("".equals(eName))
    51            eName = qName;
    52        // 當namespaceAware為false時
    53        int count = 1;
    54        while (hm_TagData.get(eName) != null) {
    55            eName = eName + count;
    56            count++;
    57        }
    58        hm_TagData.put(eName, textBuffer);
    59        echoText();
    60    }
    61    private void echoText() {
    62        if (textBuffer == null)
    63            return;
    64        String s = "" + textBuffer;
    65        textBuffer = null;
    66    }
    67
    68}
    69