本实例利用Person对象对java SAX进行学习,主要功能是将Person对象使用SAX解析为xml文档并且将xml文档解析为Person对象。
1. 定义一个person实体类
public class Person
{
private Integer id;
private String name;
private Integer age;
public Person()
{
}
public Person(Integer id, String name, Integer age)
{
super();
this.id = id;
this.name = name;
this.age = age;
}
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Integer getAge()
{
return age;
}
public void setAge(Integer age)
{
this.age = age;
}
@Override
public String toString()
{
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
2. SAX解析示例代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.DefaultHandler;
public class Main
{
private static String path = Main.class.getResource("").getPath() + "person.xml";
public static void writer() throws TransformerConfigurationException, FileNotFoundException, SAXException, IllegalArgumentException, IllegalAccessException {
List<Person> persons=new ArrayList<Person>();
persons.add(new Person(1,"张三",18));
persons.add(new Person(2,"李四",29));
SAXTransformerFactory factory=(SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerHandler handler=factory.newTransformerHandler();
Transformer transformer=handler.getTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // 换行
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); // 字符集
Result result = new StreamResult(new FileOutputStream(new File(path)));
handler.setResult(result);
AttributesImpl attr=new AttributesImpl();
handler.startDocument();
handler.startElement("", "", "root", attr);
for (Person person : persons)
{
attr.clear();
handler.startElement("", "", "person",attr);
for(Field field: person.getClass().getDeclaredFields()) {
field.setAccessible(true);
attr.clear();
Object value = field.get(person);
handler.startElement("", "",field.getName(),attr);
handler.characters(value.toString().toCharArray(), 0, value.toString().length());
handler.endElement("", "", field.getName());
}
handler.endElement("", "", "person");
}
handler.endElement("", "", "root");
handler.endDocument();
System.out.println("写入完成!");
}
public static void reader() throws ParserConfigurationException, SAXException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
List<Person> persons=new ArrayList<Person>();
Class<?> clazz = Class.forName(Person.class.getName());
Field[] personFields = clazz.getDeclaredFields();
List<String> personAttr=new ArrayList<>();
for (Field field: personFields)
{
field.setAccessible(true);
personAttr.add(field.getName().toLowerCase());
}
saxParser.parse(new File(path), new DefaultHandler() {
Object person = null;
Field field=null;
@SuppressWarnings("deprecation")
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
field=null;
if (qName=="person")
{
try
{
person=clazz.newInstance();
}
catch (InstantiationException | IllegalAccessException e)
{
e.printStackTrace();
}
}else if(personAttr.contains(qName.toLowerCase())){
try
{
field=clazz.getDeclaredField(qName);
}
catch (NoSuchFieldException | SecurityException e)
{
e.printStackTrace();
}
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
field=null;
if (qName=="person")
{
persons.add((Person)person);
}
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
try
{
if (field!=null)
{
field.setAccessible(true);
String type = field.getGenericType().getTypeName();
switch (type)
{
case "java.lang.String":
field.set(person, new String(ch,start,length));
break;
case "java.lang.Integer":
field.set(person,Integer.valueOf(new String(ch,start,length)));
break;
default:
break;
}
}
}
catch (IllegalArgumentException | IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
System.out.println("读出的数据:"+persons);
}
public static void main(String[] args) throws TransformerConfigurationException, IllegalArgumentException, IllegalAccessException, SAXException, ParserConfigurationException, IOException, ClassNotFoundException, InstantiationException
{
writer();
reader();
}
}