- public class MyContentHandler extends DefaultHandler {
- String hisname, address, money, sex, status;
- String tagName;
-
- //當開始解析文檔時,觸發這個函數
- public void startDocument() throws SAXException {
- System.out.println("````````begin````````");
- }
- //當結束解析文檔時,觸發這個函數
- public void endDocument() throws SAXException {
- System.out.println("````````end````````");
- }
- //當掃描到開始標籤時,觸發這個函數。
- public void startElement(String namespaceURI, String localName,
- String qName, Attributes attr) throws SAXException {
- //使用全局變量tagName做爲當前正在解析節點的標記。
- tagName = localName;
- if (localName.equals("worker")) {
-
- for (int i = 0; i < attr.getLength(); i++) {
- //打印其中某個屬性的名稱和屬性值
- System.out.println(attr.getLocalName(i) + "=" + attr.getValue(i));
- }
- }
- }
-
- public void endElement(String namespaceURI, String localName, String qName)
- throws SAXException {
-
- tagName = "";
- if (localName.equals("worker")) {
- this.printout();
- }
- }
- //當掃描到標籤內容時,觸發這個函數。標籤的內容存儲在字符數組中。
- public void characters(char[] ch, int start, int length)
- throws SAXException {
- //首先判斷當前掃描到的標籤,而後根據當前標籤判斷標籤內容
- if (tagName.equals("name"))
- hisname = new String(ch, start, length);
- else if (tagName.equals("sex"))
- sex = new String(ch, start, length);
- else if (tagName.equals("status"))
- status = new String(ch, start, length);
- else if (tagName.equals("address"))
- address = new String(ch, start, length);
- else if (tagName.equals("money"))
- money = new String(ch, start, length);
- }
-
- private void printout() {
- System.out.print("name: ");
- System.out.println(hisname);
- System.out.print("sex: ");
- System.out.println(sex);
- System.out.print("status: ");
- System.out.println(status);
- System.out.print("address: ");
- System.out.println(address);
- System.out.print("money: ");
- System.out.println(money);
- System.out.println();
- }
-
- }
|