XML格式文本 与 JavaBean 相互转换
发布时间:2020-12-16 00:09:52 所属栏目:百科 来源:网络整理
导读:首先我封装了两个方法,XML—-JavaBean 和 JavaBean—-XML 之间的转换: /** * 将 对象 转换成 xml * @param clazz 目标类 * @throws Exception 异常 */ public static void ObjectToXML (Object obj) throws Exception{ JAXBContext ctx = JAXBContext.newIn
首先我封装了两个方法,XML—->JavaBean 和 JavaBean—->XML 之间的转换: /** * 将 对象 转换成 xml * @param clazz 目标类 * @throws Exception 异常 */
public static void ObjectToXML(Object obj) throws Exception{
JAXBContext ctx = JAXBContext.newInstance(obj.getClass());//动态判定类型
Marshaller marchaller = ctx.createMarshaller();
marchaller.marshal(obj,System.out);
}
/** * 将 xml 转换成 对象 * @param obj 目标类型 * @param xmlStr xml字符串 * @throws Exception 异常 */
public static Object XMLToObject(Object obj,String xmlStr) throws Exception{
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Unmarshaller unmarshaller = context.createUnmarshaller();
Object object = unmarshaller.unmarshal(new StringReader(xmlStr));
return object;
}
测试程序: public static void main(String[] args) throws Exception {
Student stu = new Student();
stu.setStuName("Bla");
stu.setScore(79);
stu.setAge("20");
stu.setDate(new Date());
//对象转换成xml
ObjectToXML(stu);
//将 xml 装换成 对象
String xmlStr = "<?xml version="1.0" encoding="UTF-8" standalone="yes"?><student><age>20</age><date>2015-12-07T19:49:52.236+08:00</date><score>79</score><stuName>Bla</stuName></student>";
System.out.println("将 xml 装换成 对象 n");
Object xmlToObject = XMLToObject(new Student(),xmlStr);
String studentInfo = ((Student)xmlToObject).toString();
System.out.println(studentInfo);
}
测试程序需要的实体类: @XmlRootElement
public class Student {
private String stuName;
private String age;
private Date date;
private int score;
public Student() {
super();
}
public Student(String stuName,String age,Date date,int score) {
super();
this.stuName = stuName;
this.age = age;
this.date = date;
this.score = score;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "Student [stuName=" + stuName + ",age=" + age + ",date=" + date + ",score=" + score + "]";
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |