使用jaxb解析XML

在日常开发可能经常涉及到接口之间的调用,当下很多都是使用json格式的报文,但依然有一些使用的是xml格式的报文,将xml格式转为bean能高效的获取属性。

使用jaxb解析xml到bean

创建实体

import java.math.BigDecimal;
import java.util.Date;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import com.bjsasc.avfms.adapter.DateAdapter;
import com.fasterxml.jackson.annotation.JsonFormat;

import org.springframework.format.annotation.DateTimeFormat;

/**
 * 描述: .
 *
 * @since 1.0.1
 */
@Data
@XmlAccessorType(XmlAccessType.FIELD)
public class Test{
    
    private String code;
    private Integer type;
    private BigDecimal bigDecimal;
    private Long aLong;
    @XmlElement(name = "n_is")
    private Boolean nIs;
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @XmlJavaTypeAdapter(DateAdapter.class)
    private Date date;

}

其中date类型需要添加注解@XmlJavaTypeAdapter(DateAdapter.class)

创建DateAdapter类,处理日期格式

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.bind.annotation.adapters.XmlAdapter;

/**
 * 描述: .
 * <p>
 * Copyright: Copyright (c) 2021.
 *
 * @since 1.0.1
 */
public class DateAdapter extends XmlAdapter<String, Date> {

    private SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Date unmarshal(String v) throws Exception {
        return yyyyMMddHHmmss.parse(v);
    }

    @Override
    public String marshal(Date v) throws Exception {
        return yyyyMMddHHmmss.format(v);
    }
}

当xml中为多个相同的实体时再创建一个实体

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * 描述: .
 * <p>
 * Copyright: Copyright (c) 2021.
 *
 * @since 1.0.1
 */
@Data
@XmlRootElement(name = "Tests")
@XmlAccessorType(XmlAccessType.FIELD)
public class Tests {
    @XmlElement(name = "Test")
    private List<Test> tests;
}

创建XmlUtils

import java.io.StringReader;
import java.io.StringWriter;

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

/**
 * 描述: .
 * <p>
 * Copyright: Copyright (c) 2021.
 *
 * @since 1.0.1
 */
public class XmlUtils {
    /**
     * bean转成xml
     * @param t :
     * @return string
     */
    public static <T> String beanToXml(T t) throws JAXBException {
        //获得 JAXBContext 类的新实例。参数为类的地址
        JAXBContext context = JAXBContext.newInstance(t.getClass());
        //创建一个可以用来将 java 内容树转换为 XML 数据的 Marshaller 对象。
        Marshaller m = context.createMarshaller();
        //创建一个StringWriter流将接收到的对象流写入xml字符串
        StringWriter sw = new StringWriter();
        //调用marshal方法进行转换
        m.marshal(t,sw);
        //将读取到的StringWriter流转成String返回
        return sw.toString();
    }

    /**
     * bean转成xml(泛型使用)
     * @param t :
     * @return java.lang.String
     */
    public static <T> String beanToXml(T t, Class c) throws JAXBException {
        //获得 JAXBContext 类的新实例。参数为类的地址
        JAXBContext context = JAXBContext.newInstance(t.getClass(),c);
        //创建一个可以用来将 java 内容树转换为 XML 数据的 Marshaller 对象。
        Marshaller m = context.createMarshaller();
        //创建一个StringWriter流将接收到的对象流写入xml字符串
        StringWriter sw = new StringWriter();
        //调用marshal方法进行转换
        m.marshal(t,sw);
        //将读取到的StringWriter流转成String返回
        return sw.toString();
    }

    /**
     * xml 转成 bean
     * @param xml :
     * @param t :
     * @return T
     */
    public static <T> T xmlToBean(String xml, T t) throws JAXBException {
        //获得 JAXBContext 类的新实例。参数为类的地址
        JAXBContext context = JAXBContext.newInstance(t.getClass());
        //创建一个可以用来将 XML 数据转换为 java 内容树的 Unmarshaller 对象。
        Unmarshaller um = context.createUnmarshaller();
        //创建一个StringReader将xml报文转成流
        StringReader sr = new StringReader(xml);
        //调用unmarshal进行转换,并把Object类型强转为调用者的类型
        t = (T) um.unmarshal(sr);
        //将对象返回给调用者
        return t;
    }

    /**
     * xml 转成 bean(泛型使用)
     * @param t, t
     * @param xml xml
     * @param c t]
     * @return T
     */
    public static <T> T xmlToBean(String xml, T t, Class c) throws JAXBException {
        //获得 JAXBContext 类的新实例。参数为类的地址
        javax.xml.bind.JAXBContext context = JAXBContext.newInstance(t.getClass(),c);
        //创建一个可以用来将 XML 数据转换为 java 内容树的 Unmarshaller 对象。
        Unmarshaller um = context.createUnmarshaller();
        //创建一个StringReader将xml报文转成流
        StringReader sr = new StringReader(xml);
        //调用unmarshal进行转换,并把Object类型强转为调用者的类型
        t = (T) um.unmarshal(sr);
        //将对象返回给调用者
        return t;
    }

}

使用main方法进行测试

public static void main(String[] args) {
        List<Test> testList = new ArrayList<>();
        Test test = new Test();
        test.setCode("code");
        test.setType(1);
        test.setBigDecimal(new BigDecimal("1.01"));
        test.setaLong(1L);
        test.setnIs(true);
        test.setDate(new Date());
        testList.add(test);

        Test test1 = new Test();
        test1.setCode("code1");
        test1.setType(2);
        test1.setBigDecimal(new BigDecimal("2.01"));
        test1.setaLong(2L);
        test1.setnIs(false);
        test1.setDate(new Date());
        testList.add(test1);

        Tests tests = new Tests();
        tests.setTests(testList);
        System.out.println("数据组装完成的对象bean为:\n" + tests);
        try {
            System.out.println("================== bean转成xml格式  ======================");
            String xml = XmlUtils.beanToXml(tests);
            System.out.println("bean转成xml格式为:\n" + xml);
            System.out.println("=================== xml转成bean格式 =====================");
            tests = XmlUtils.xmlToBean(xml, tests, Materials.class);
            System.out.println("xml转成bean格式为:\n" + tests);
        } catch (JAXBException ex) {
            ex.printStackTrace();
        }
    }

测试结果

数据组装完成的对象bean为:
Tests{tests=[Test{code='code', type=1, bigDecimal=1.01, aLong=1, nIs=true, date=Thu Sep 23 17:32:14 CST 2021}, Test{code='code1', type=2, bigDecimal=2.01, aLong=2, nIs=false, date=Thu Sep 23 17:32:14 CST 2021}]}
================== bean转成xml格式  ======================
bean转成xml格式为:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Tests><Test><code>code</code><type>1</type><bigDecimal>1.01</bigDecimal><aLong>1</aLong><n_is>true</n_is><date>2021-09-23 17:32:14</date></Test><Test><code>code1</code><type>2</type><bigDecimal>2.01</bigDecimal><aLong>2</aLong><n_is>false</n_is><date>2021-09-23 17:32:14</date></Test></Tests>
=================== xml转成bean格式 =====================
xml转成bean格式为:
Tests{tests=[Test{code='code', type=1, bigDecimal=1.01, aLong=1, nIs=true, date=Thu Sep 23 17:32:14 CST 2021}, Test{code='code1', type=2, bigDecimal=2.01, aLong=2, nIs=false, date=Thu Sep 23 17:32:14 CST 2021}]}

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值