XML格式文本 与 JavaBean 相互转换

首先我封装了两个方法,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);
     }

测试程序需要的实体类:
注意:使用Java自带的转换有一点不好,就是实体类前面需要加 @XmlRootElement 注解

@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 + "]";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值