Java处理XML文档的StAX方式

package cn.rock.service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import cn.rock.bean.Person;

public class StAXParseService {
 private List<Person> personList = null;
 private Person person = null;
 
 public void displayXML(){
  StAXParseXML();
  Iterator<Person> iter = personList.iterator();
  while(iter.hasNext()){
   Person person = (Person)iter.next();
   System.out.println(person.toString());
  }
 }
 
 public void StAXParseXML(){
  personList = new ArrayList<Person>();
  
  XMLInputFactory factory = XMLInputFactory.newInstance();
  try {
   XMLStreamReader xmlReader = factory.createXMLStreamReader(new FileInputStream("E:\\Workspaces\\MyEclipse for Spring 8.6\\xml\\bin\\person.xml"));
   while(xmlReader.hasNext()){
    int event = xmlReader.next();
    if(event == XMLStreamConstants.START_ELEMENT){
     if("person".equals(xmlReader.getName().toString())){
      person = new Person();
      String id = xmlReader.getAttributeValue(null, "id");
      System.out.println("id-------" + id);
      person.setId(new Integer(id));
      
     }else if("name".equals(xmlReader.getName().toString())){
      String name = xmlReader.getElementText();
      System.out.println("name-----" + name);
      person.setName(name);
     }else if("age".equals(xmlReader.getName().toString())){
      String age = xmlReader.getElementText();
      System.out.println("age------" + age);
      person.setAge(new Short(age));
     }else if("address".equals(xmlReader.getName().toString())){
      String address = xmlReader.getElementText();
      System.out.println("address------" + address);
      person.setAddress(address);
     }
     
//     System.out.println(xmlReader.getEventType() + " " + xmlReader.getEventType() + " " + xmlReader.getName());
    }else if(event == XMLStreamConstants.END_ELEMENT){
     if("person".equals(xmlReader.getName().toString())){
      personList.add(person);
      person = null;
     }
    }
   }
   

  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (XMLStreamException e) {
   e.printStackTrace();
  }
 }
}

你可能感兴趣的:(java,xml,String,MyEclipse,Integer,文档)