xml2

package com.xml.parse;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author dongwen
 *
 */
public class PersonDefaultHandler extends DefaultHandler {

 private List persons;

 // 记录当前person
 private Person person;

 private String tag;

 /**
  * 重写父类的开始文档方法,用于初始化
  */
 @Override
 public void startDocument() throws SAXException {

  persons = new ArrayList();
 }

 @Override
 public void startElement(String uri, String localName, String qName,
   Attributes attributes) throws SAXException {

  if ("person".equals(localName)) {
   Integer id = new Integer(attributes.getValue(0));
   person = new Person();
   person.setId(id);
  }
  tag = localName;
 }

 @Override
 public void characters(char[] ch, int start, int length)
   throws SAXException {
  if (tag != null) {
   String data = new String(ch, start, length);

   if ("name".equals(tag)) {
    person.setName(data);
   } else if ("age".equals(tag)) {
    person.setAge(new Short(data));
   }

  }
 }
 
 
 @Override
 public void endElement(String uri, String localName, String qName)
   throws SAXException {
  
  if("person".equals(localName)){
   persons.add(person);
   person = null;
  }
  tag = null;
 }

 public List getPersons() {
  return persons;
 }
 
 
 
}

你可能感兴趣的:(Java)