xml和對象的相互轉化

@Data//setter和getter方法,toString和equals,hashcode方法
@EqualsAndHashCode//表明重寫equals和hashcode方法
@XmlAccessorType(XmlAccessType.FIELD)
public class Classroom {
@XmlElement(name="id")
private int id;
@XmlElement(name="name")
private String name;
@XmlElement(name="grade")
private int grade;
public Classroom(int id,String name,int grade){
	this.id=id;
	this.name=name;
	this.grade=grade;
}
public Classroom(){//必須包含無參數的構造方法
	super();
}
}

@Data
@EqualsAndHashCode(callSuper=false)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="student")
@ToString(callSuper=true)
public class Student {
@XmlAttribute(name="ha")
private String ha;
@XmlElement(name="id")
private Integer id;
@XmlElement(name="name")
private String name;
@XmlElement(name="age")
private int age;
@XmlElement(name="classroom")
private Classroom classroom;
public Student(){}

測試:





public class Test1 {
   @Test//Java對象轉換爲xml
	public void beanToXml(){
	  Classroom classroom=new Classroom(1,"軟件工程",4);
	  Student student=new Student();
	  student.setClassroom(classroom);
	  student.setHa("你好哈");
	  try{
JAXBContext context=JAXBContext.newInstance(Student.class);
Marshaller marshaller=context.createMarshaller();//將Java序列化爲xml
marshaller.marshal(student, System.out);
System.out.println();
	  }
	  catch(JAXBException e){
		  e.printStackTrace();
	  }
	}
	
	@Test//xml數據轉換爲Java對象
	public void XmlStringToBean(){
	String xmlStr="<?xml version=\'1.0\' encoding=\'UTF-8\' standalone=\'yes\' ?>"
				+ "<student><age>22</age><classroom><grade>4</grade><id>1</id><name>軟件工程</name>"
				+ "</classroom><id>101</id><name>張三</name></student>";
		try{
JAXBContext context=JAXBContext.newInstance(Student.class);//是應用的入口,用於管理XML/JAVA綁定信息Unmarshaller unmarshaller=context.createUnmarshaller();//unmarshaller接口,將xml數據反序列化爲Java對象
Student student=(Student)unmarshaller.unmarshal(new StringReader(xmlStr));
System.out.println(student.getAge());
System.out.println(student.getClassroom().getName());
		}
		catch(JAXBException e){
			e.printStackTrace();
		}
	}
}
相關文章
相關標籤/搜索