JAXB实现XML与Java对象转换

发布时间:2020-05-14 13:42:04 作者:Leah
来源:亿速云 阅读:98

今天小编给大家分享的是JAXB实现XML与Java对象转换的实例展示,相信大部分人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,话不多说,一起往下看吧。

JAXB是Java Architecture for XML Binding的缩写,用于在Java类与XML之间建立映射,能够帮助开发者很方便的將XML和Java对象进行相互转换。
本文以一个简单的例子介绍JAXB的使用,首先我们需要了解一下JAXB常用的API。

我们需要进行绑定的Java Bean内容如下:
Employee.java

package net.csdn.beans;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)  
@XmlRootElement  @XmlType(name = "Employee", propOrder = { "name", "age", "role", "gender" }) 
public class Employee {
    private String name;    
    private String gender;    
    private int age;    
    private String role;    
    public String getName() {        
    return name;
    }    public void setName(String name) {        
    this.name = name;
    }    public String getGender() {        
    return gender;
    }    public void setGender(String gender) {        
    this.gender = gender;
    }    public int getAge() {        
    return age;
    }    public void setAge(int age) {        
    this.age = age;
    }    public String getRole() {        
    return role;
    }    public void setRole(String role) {        
    this.role = role;
    }    @Override
    public String toString() {        
    return "Employee:: Name=" + this.name + " Age=" + this.age + " Gender="
                + this.gender + " Role=" + this.role;
    }

}

需要转换为Java对象的XML文件内容如下:
employee.xml

<?xml version="1.0"?><employee id="1">
    <name>Pankaj</name>
    <age>29</age>
    <role>Java Developer</role>
    <gender>Male</gender></employee>

接下来编写测试用例代码:
TestJAXB.java

package net.csdn.test;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import net.csdn.beans.Employee;
import org.junit.Test;public class TestJAXB {
    @Test
    public void testXml2Obj() throws Exception {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("employee.xml");
        byte[] bytes = new byte[is.available()];
        is.read(bytes);
        String xmlStr = new String(bytes);
        JAXBContext context = JAXBContext.newInstance(Employee.class);  
        Unmarshaller unmarshaller = context.createUnmarshaller();  
        Employee emp = (Employee) unmarshaller.unmarshal(new StringReader(xmlStr));
        System.out.println(emp);
    }

    @Test
    public void testObj2Xml() {
        Employee  emp = new Employee();
        emp.setAge(10);
        emp.setGender("Male");
        emp.setName("Jane");
        emp.setRole("Teacher");
        String xmlStr = TestJAXB.convertToXml(emp,"utf-8");  
        System.out.println(xmlStr);
    }

    public static String convertToXml(Object obj, String encoding) {  
        String result = null;  
        try {  
            JAXBContext context = JAXBContext.newInstance(obj.getClass());  
            Marshaller marshaller = context.createMarshaller();  
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);  

            StringWriter writer = new StringWriter();  
            marshaller.marshal(obj, writer);  
            result = writer.toString();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  

        return result;  
    } 

}

运行testObj2Xml测试方法,控制台输出:

<?xml version="1.0" encoding="utf-8" standalone="yes"?><employee>
    <name>Jane</name>
    <age>10</age>
    <role>Teacher</role>
    <gender>Male</gender></employee>

运行testXml2Obj测试方法,控制台输出:

Employee:: Name=Pankaj Age=29 Gender=Male Role=Java Developer

注:本例中使用JUnit4作为单元测试工具,在Eclipse中点击Window->Show View->OutLine菜单打开outline视图,分别在testXml2Obj和testObj2Xml方法上点击右键->Run As->JUnit Test即可。

JAXB是Java Architecture for XML Binding的缩写,用于在Java类与XML之间建立映射,能够帮助开发者很方便的將XML和Java对象进行相互转换。
本文以一个简单的例子介绍JAXB的使用,首先我们需要了解一下JAXB常用的API。

我们需要进行绑定的Java Bean内容如下:
Employee.java

package net.csdn.beans;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)  
@XmlRootElement  
@XmlType(name = "Employee", propOrder = { "name", "age", "role", "gender" }) 
public class Employee {
    private String name;    
    private String gender;    
    private int age;    
    private String role;    
    public String getName() {        
    return name;
    }    public void setName(String name) {        
    this.name = name;
    }    public String getGender() {        
    return gender;
    }    public void setGender(String gender) {        
    this.gender = gender;
    }    public int getAge() {        
    return age;
    }    public void setAge(int age) {        
    this.age = age;
    }    public String getRole() {        
    return role;
    }    public void setRole(String role) {        
    this.role = role;
    }    @Override
    public String toString() {        
    return "Employee:: Name=" + this.name + " Age=" + this.age + " Gender="
                + this.gender + " Role=" + this.role;
    }

}

需要转换为Java对象的XML文件内容如下:
employee.xml

<?xml version="1.0"?><employee id="1">
    <name>Pankaj</name>
    <age>29</age>
    <role>Java Developer</role>
    <gender>Male</gender></employee>

接下来编写测试用例代码:
TestJAXB.java

package net.csdn.test;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import net.csdn.beans.Employee;
import org.junit.Test;
public class TestJAXB {
    @Test
    public void testXml2Obj() throws Exception {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("employee.xml");
        byte[] bytes = new byte[is.available()];
        is.read(bytes);
        String xmlStr = new String(bytes);
        JAXBContext context = JAXBContext.newInstance(Employee.class);  
        Unmarshaller unmarshaller = context.createUnmarshaller();  
        Employee emp = (Employee) unmarshaller.unmarshal(new StringReader(xmlStr));
        System.out.println(emp);
    }

    @Test
    public void testObj2Xml() {
        Employee  emp = new Employee();
        emp.setAge(10);
        emp.setGender("Male");
        emp.setName("Jane");
        emp.setRole("Teacher");
        String xmlStr = TestJAXB.convertToXml(emp,"utf-8");  
        System.out.println(xmlStr);
    }

    public static String convertToXml(Object obj, String encoding) {  
        String result = null;  
        try {  
            JAXBContext context = JAXBContext.newInstance(obj.getClass());  
            Marshaller marshaller = context.createMarshaller();  
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);  

            StringWriter writer = new StringWriter();  
            marshaller.marshal(obj, writer);  
            result = writer.toString();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  

        return result;  
    } 

}

运行testObj2Xml测试方法,控制台输出:

<?xml version="1.0" encoding="utf-8" standalone="yes"?><employee>
    <name>Jane</name>
    <age>10</age>
    <role>Teacher</role>
    <gender>Male</gender></employee>

运行testXml2Obj测试方法,控制台输出:

Employee:: Name=Pankaj Age=29 Gender=Male Role=Java Developer

注:本例中使用JUnit4作为单元测试工具,在Eclipse中点击Window->Show View->OutLine菜单打开outline视图,分别在testXml2Obj和testObj2Xml方法上点击右键->Run As->JUnit Test即可。

以上就是JAXB实现XML与Java对象转换的具体操作,代码详细清楚,如果在日常工作遇到这个问题,希望你能通过这篇文章解决问题。如果想了解更多相关内容,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. java对象如何转换为xml格式
  2. Jaxb2实现Bean与xml互转的案例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java jaxb xml

上一篇:04搭建cdh 集群角色规划

下一篇:Redis Desktop Manager安装

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》