#Java Xml转换 JAXB的使用(jdk8)

后续更新JDK10的JAXB的使用

jdk10链接:
参考:https://blog.csdn.net/zhouzhiwengang/article/details/56679004

JAXB所需要使用到的类

  • JAXBContext类用于绑定Java实体与XML之间的信息
  • Marshaller 接口,将Java实体序列化为XML数据.
  • Unmarshaller接口,将XML数据反序列化为Java对象

JAXB所需要使用的注解

  • @XmlType,将Java中的变量与Xml中的标签做对应(变量名与Xml中的标签名相同)
  • @XmlAccessorType
    1.@XmlAccessType(XmlAccessorType.FIELD)自动映射类中的属性和xml中的标签,绑定类中每一个非静态的、非瞬态的(@XmlTransien)到XML。注:标签名与变量名要一致.除了指定该变量名的映射关系(如:@XmlElement,@XmlElementWrapper)
  • @XmlAccessOrder 控制JAXB绑定类中属性和字段的排序
  • @XmlJavaTypeAdapter 适用定制的适配器(扩展抽象类XmlAdapter覆盖两个序列化方法marshal()和unmarshal()方法),以序列化Java类为Xml
  • @XmlElementWrapper ,对于数据或集合(即包含多个元素的成员变量),生成一个包装该数组或集合的XML元素
  • @XmlRootElement,指定Xml的根目录为指定类
  • @XmlElement 将Java类的一个变量映射到与标签同名的一个XML元素
  • @XmlAttribute 将Java类的一个变量映射到与标签同名的一个XML属性

用到最多的是:

@XmlRootElement
@XmlElement
@XmlElementWrapper
@XmlAccessType(XmlAccessType.FIELD)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Employee")
@Data
public class Employee {
    private Integer id;
    private String code;
    @XmlElement(name = "gg_name")
    private String name;
    private String telephone;
    private Integer sex;
    private Dept dept;
    private List<Dept> depts;
}
注:这里可结合使用lombok注解

效果

<Employee>
    <id>1</id>
    <code>002</code>
    <gg_name>zhangzhang</gg_name>
    <telephone>15698499195</telephone>
    <sex>2</sex>
    <dept>
        <deptId>7acd2d56-2c77-4ec5-94de-1d0df42195ea</deptId>
        <deptName>开发部</deptName>
    </dept>
    <depts>
        <deptId>d9e8cff2-145a-43d5-ae77-8a3989737f47</deptId>
        <deptName>部门00</deptName>
    </depts>
    <depts>
        <deptId>43fffeb3-82e1-456a-896e-b6b4220aefbb</deptId>
        <deptName>部门01</deptName>
    </depts>
    <depts>
        <deptId>45d1ecea-c5f5-4a39-94ac-71b3a8e124e1</deptId>
        <deptName>部门02</deptName>
    </depts>
    <depts>
        <deptId>33a07a23-86b0-4fe3-8d7b-6912921dcd95</deptId>
        <deptName>部门03</deptName>
    </depts>
    <depts>
        <deptId>c69057b9-bc9a-44fb-9ffb-9405230c640d</deptId>
        <deptName>部门04</deptName>
    </depts>
</Employee>

可以使用@XmlElementWrapper创建更深层的关系

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Employee")
@Data
public class Employee {
    private Integer id;
    private String code;
    @XmlElement(name = "gg_name")
    private String name;
    private String telephone;
    private Integer sex;
    private Dept dept;
    /**
     * @XmlElementWrapper 指定外层Xml的标签名
     * @XmlElement 指定集合中的实体的标签名
     */
    @XmlElementWrapper(name = "depts")
    @XmlElement(name = "dept")
    private List<Dept> depts;
}

效果

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Employee>
    <id>1</id>
    <code>002</code>
    <gg_name>zhangzhang</gg_name>
    <telephone>15698499195</telephone>
    <sex>2</sex>
    <dept>
        <deptId>e712184d-d6b3-4a7f-bb24-ab002b2c1c51</deptId>
        <deptName>开发部</deptName>
    </dept>
    <depts>
        <dept>
            <deptId>f02982da-be9e-41f5-a827-cabf8765d868</deptId>
            <deptName>部门00</deptName>
        </dept>
        <dept>
            <deptId>481aded6-ea85-4e8b-a915-35c786ab378e</deptId>
            <deptName>部门01</deptName>
        </dept>
        <dept>
            <deptId>9d2205b2-5c25-4610-ac65-f11889a63330</deptId>
            <deptName>部门02</deptName>
        </dept>
        <dept>
            <deptId>c06702f1-5b13-4a01-88a4-99b3da355a08</deptId>
            <deptName>部门03</deptName>
        </dept>
        <dept>
            <deptId>59ae0a22-8cbf-4f4a-b748-20122a812ccd</deptId>
            <deptName>部门04</deptName>
        </dept>
    </depts>
</Employee>

工具类

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class XmlUtil {

    /**
     * 将对象直接转换成String类型的XML输出
     * @param obj 指定对象(包含XML注解)
     * @return 返回XML
     */
    public static String convertToXml(Object obj) {
        // 创建输出流
        StringWriter sw = new StringWriter();
        try {
            // 利用jdk中自带的转换类实现
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            // 将对象序列化为Xml
            Marshaller marshaller = context.createMarshaller();
            // 格式化Xml输出的格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            // 将对象转换成输出流形式的XML
            marshaller.marshal(obj, sw);

        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return sw.toString();
    }

    /**
     * 将file类型的xml装换成对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T convertXmlFileToT(Class<T> clazz,String xmlPath) {
        T xmlObject = null;
        FileReader fr = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshal =  context.createUnmarshaller();
            fr = new FileReader(xmlPath);
            xmlObject = (T) unmarshal.unmarshal(fr);
        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fr != null) {
                    fr.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        return xmlObject;
    }

        /**
     * 将String类型的Xml转换成对象
     */
    @SuppressWarnings("unchecked")
    public <T> T convertXmlStrToT(Class<T> clazz, String xmlStr) {
        T xmlObject = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            // 进行将Xml转成对象的核心接口
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader sr = new StringReader(xmlStr);
            xmlObject = (T) unmarshaller.unmarshal(sr);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return xmlObject;
    }

    /**
     * 根据xml路径将其转为对象
     */
    public <T> String convertPathToT(Class<T> clazz, String path) {
        JAXBContext context = null;
        // 创建输出流
        FileWriter fw = null;
        try {
            context = JAXBContext.newInstance(clazz);
            Marshaller marshaller = context.createMarshaller();
            // 格式化xml输出的格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            // 将对象转换成输出流形式的xml
            try {
                fw = new FileWriter(path);
            } catch (Exception e) {
                e.printStackTrace();
            }
            marshaller.marshal(clazz, fw);
        } catch (JAXBException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return fw.toString();
    }
}

主测试类

public class XmlMain {

    @Test
    public void test01() {
        Employee employee = new Employee();
        employee.setId(1);
        employee.setCode("002");
        employee.setName("zhangzhang");
        employee.setSex(2);
        employee.setTelephone("15698499195");
        
        Dept dept = new Dept();
        dept.setDeptId(UUID.randomUUID().toString());
        dept.setDeptName("开发部");
        employee.setDept(dept);
        
        List<Dept> list = new ArrayList<>();
        for(int i = 0;i < 5;i++) {
            Dept d = new Dept();
            d.setDeptId(UUID.randomUUID().toString());
            d.setDeptName("部门0" + i);
            list.add(d);
        }
        employee.setDepts(list);
        String xml = XmlUtil.convertToXml(employee);
        System.out.println(XmlMain.class.getClass().getResource("/employee.xml").getPath());
        File file = new File(XmlMain.class.getClass().getResource("/employee.xml").getPath());
        OutputStreamWriter osw = null;
        try {
            FileOutputStream fos = new FileOutputStream(file);
            osw = new OutputStreamWriter(fos, "utf-8");
            osw.write(xml);
            osw.flush();
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(osw != null) {
                    osw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void test02() {
        Employee employee = XmlUtil.convertXmlFileToT(Employee.class, XmlMain.class.getClass().getResource("/employee.xml").getPath());
        List<Dept> depts = new ArrayList<>();
        depts = employee.getDepts();
        for(Dept dept : depts) {
            System.out.println(dept);
        }
        System.out.println(employee);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,765评论 18 399
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 22,545评论 1 92
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • 2017年春 最喜欢描写春天的诗当属《江南春》了 千里莺啼绿映红, 水村山郭酒旗风。 南朝四百八十寺, 多少楼台烟...
    大头诺阿诺阅读 337评论 6 1
  • 北京开放大学是由北京市政府举办,北京市教委主管,以现代信息技术为支撑,面向成人开展远程开放教育的新型高等学校。其前...
    现任男友阅读 465评论 0 0