01 利用javax的api解析xml文件
一、处理xml的方式这里记录以下两种:
1、JAXB(Java Architecture for XML Binding)
SAX,全称Simple API for XML,既是一种接口,也是一种软件包。它是一种XML解析的替代方法。SAX不同于DOM解析,它逐行扫描文档,一边扫描一边解析。
2、STAX(Stream API for XML) 处理xml
stream(oracle公司提供的)-->Stax
xStream可以轻易的将Java对象和xml文档相互转换,而且可以修改某个特定的属性和节点名称,而且也支持json的转换;
1-1.1实例:JAXB做java对象与xml文件的相互转换
第一步:创建classroom,和student实体类。
package org.itat.xml;
public class ClassRoom {
private int id;
private String name;
private int grade;//班级
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public ClassRoom(int id, String name, int grade) {
super();
this.id = id;
this.name = name;
this.grade = grade;
}
public ClassRoom() {
super();
}
}
创建student类:
package org.itat.xml;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement//设置根元素
public class Student {
private int id;
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private ClassRoom classroom;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ClassRoom getClassroom() {
return classroom;
}
public void setClassroom(ClassRoom classroom) {
this.classroom = classroom;
}
public Student() {
super();
}
public Student(int id, String name, int age, ClassRoom classroom) {
super();
this.id = id;
this.name = name;
this.age = age;
this.classroom = classroom;
}
}
第二步:创建测试类测试相互转换:
package org.itat.xml;import java.io.StringReader;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBException;import javax.xml.bind.Marshaller;import javax.xml.bind.Unmarshaller;import org.junit.Test;public class TestJaxb {/** * JAXBContext 将java对象转换为xml文件。 * Marshaller接口,将Java对象序列化为XML数据。 * @XmlRootElement,将Java类或枚举类型映射到XML元素。作为根元素,用在实体类上。 */@Testpublic void test01(){try {JAXBContext ctx=JAXBContext.newInstance(Student.class);Marshaller marshaller=ctx.createMarshaller();Student student =new Student(1, "张三", 21,new ClassRoom(1, "10计算机应用技术", 2010));marshaller.marshal(student,System.out);//System.out是标准输出流} catch (JAXBException e) {e.printStackTrace();}}/** * JAXBContext将xml文件解析成java对象 * Unmarshaller接口,将XML数据反序列化为Java对象。 */@Testpublic void test02(){String xml="212010110计算机应用技术1张三";JAXBContext ctx;try {ctx = JAXBContext.newInstance(Student.class);Unmarshaller um=ctx.createUnmarshaller();Student student=(Student)um.unmarshal(new StringReader(xml));System.out.println(student.getName()+","+student.getClassroom().getName());} catch (JAXBException e) {e.printStackTrace();}}}