XML格式文本 与 JavaBean 相互转换

前端之家收集整理的这篇文章主要介绍了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 + "]";
    }
}

猜你在找的XML相关文章