XML与javabean互转

2021-11-23  本文已影响0人  阿杰_96c5

XML与javabean互转

第三方接口返回一个XML字符串

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ESBEntry>
    <AccessControl>
        <UserName>YBF</UserName>
        <Password>123</Password>
        <SysFlag>1</SysFlag>
        <Fid>BS10001</Fid>
    </AccessControl>
    <MessageHeader>
        <Fid>BS10001</Fid>
        <SourceSysCode>S55</SourceSysCode>
        <TargetSysCode>S02</TargetSysCode>
        <MsgDate>2021-05-27 04:58:24</MsgDate>
    </MessageHeader>
    <RequestOption>
        <onceFlag></onceFlag>
        <startNum></startNum>
        <endNum></endNum>
    </RequestOption>
    <MsgInfo>
        <Msg></Msg>
        <query item="INVALID_FLAG" compy=" = " value="'0'" splice=" and "/>
    </MsgInfo>
</ESBEntry>

https://www.freeformatter.com/xsd-generator.html#ad-output页面中将xml转换为xsd文件

image-20210811172626016.png image-20210811172645044.png

将生成的xsd文件保存到本地

使用xjc命令将xsd文件转换成 javabean

PS C:\Users\Administrator\Desktop> xjc 123.xsd
正在解析模式...
正在编译模式...
generated\ESBEntry.java
generated\ObjectFactory.java
PS C:\Users\Administrator\Desktop>

自动生成的javabean

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "accessControl",
    "messageHeader",
    "requestOption",
    "msgInfo"
})
@XmlRootElement(name = "ESBEntry")
@Data
@AllArgsConstructor //生成全参数构造函数
@NoArgsConstructor//生成无参构造函数
@Builder
public class ESBEntry {

    @XmlElement(name = "AccessControl", required = true)
    protected AccessControl accessControl;
    @XmlElement(name = "MessageHeader", required = true)
    protected MessageHeader messageHeader;
    @XmlElement(name = "RequestOption", required = true)
    protected RequestOption requestOption;
    @XmlElement(name = "MsgInfo", required = true)
    protected MsgInfo msgInfo;


    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "userName",
        "password",
        "sysFlag",
        "fid"
    })
    @Data
    @AllArgsConstructor //生成全参数构造函数
    @NoArgsConstructor//生成无参构造函数
    @Builder
    public static class AccessControl {

        @XmlElement(name = "UserName", required = true)
        protected String userName;
        @XmlElement(name = "Password")
        protected String password;
        @XmlElement(name = "SysFlag")
        protected String sysFlag;
        @XmlElement(name = "Fid", required = true)
        protected String fid;

    }



    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "fid",
        "sourceSysCode",
        "targetSysCode",
        "msgDate"
    })
    @Data
    @AllArgsConstructor //生成全参数构造函数
    @NoArgsConstructor//生成无参构造函数
    @Builder
    public static class MessageHeader {

        @XmlElement(name = "Fid", required = true)
        protected String fid;
        @XmlElement(name = "SourceSysCode", required = true)
        protected String sourceSysCode;
        @XmlElement(name = "TargetSysCode", required = true)
        protected String targetSysCode;
        @XmlElement(name = "MsgDate", required = true)
        protected String msgDate;

    }

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
            "onceFlag",
            "startNum",
            "endNum"
    })
    @Data
    @AllArgsConstructor //生成全参数构造函数
    @NoArgsConstructor//生成无参构造函数
    @Builder
    public static class RequestOption {

        @XmlElement(required = true)
        protected String onceFlag;
        @XmlElement(required = true)
        protected String startNum;
        @XmlElement(required = true)
        protected String endNum;

    }



    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "msg",
        "query"
    })
    @Data
    @AllArgsConstructor //生成全参数构造函数
    @NoArgsConstructor//生成无参构造函数
    @Builder
    public static class MsgInfo {

        @XmlElement(name = "Msg", required = true)
        protected String msg;
        protected List<Query> query;


        public List<Query> getQuery() {
            if (query == null) {
                query = new ArrayList<Query>();
            }
            return this.query;
        }

        @XmlAccessorType(XmlAccessType.FIELD)
        @Data
        @AllArgsConstructor //生成全参数构造函数
        @NoArgsConstructor//生成无参构造函数
        @Builder
        public static class Query {

            @XmlAttribute(name = "item")
            protected String item;
            @XmlAttribute(name = "compy")
            protected String compy;
            @XmlAttribute(name = "value")
            protected String value;
            @XmlAttribute(name = "splice")
            protected String splice;

        }

    }

}


实体类生成工厂类

@XmlRegistry
public class ObjectFactory {


    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: generated
     *
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link ESBEntry }
     *
     */
    public ESBEntry createESBEntry(String queueName) {

        ESBEntry.AccessControl accessControl = ESBEntry.AccessControl.builder()
                .userName("YBF").password("123").sysFlag("1").fid(queueName)
                .build();
        //DateUtil.format()
        ESBEntry.MessageHeader messageHeader = ESBEntry.MessageHeader.builder()
                .fid(queueName).sourceSysCode("S55").targetSysCode("S02").msgDate(DateUtil.now())
                .build();
        ESBEntry.RequestOption requestOption = ESBEntry.RequestOption.builder()
                .onceFlag("").startNum("").endNum("").build();
        List<ESBEntry.MsgInfo.Query> querys = new ArrayList<>();
        ESBEntry.MsgInfo msgInfo = ESBEntry.MsgInfo.builder().msg("").query(querys).build();
        return ESBEntry.builder()
                .accessControl(accessControl)
                .messageHeader(messageHeader)
                .requestOption(requestOption)
                .msgInfo(msgInfo)
                .build();

    }

    /**
     * Create an instance of {@link ESBEntry.MsgInfo }
     *
     */
    public ESBEntry.MsgInfo createESBEntry1MsgInfo() {
        return new ESBEntry.MsgInfo();
    }

    /**
     * Create an instance of {@link ESBEntry.AccessControl }
     *
     */
    public ESBEntry.AccessControl createESBEntry1AccessControl() {
        return new ESBEntry.AccessControl();
    }

    /**
     * Create an instance of {@link ESBEntry.MessageHeader }
     *
     */
    public ESBEntry.MessageHeader createESBEntry1MessageHeader() {
        return new ESBEntry.MessageHeader();
    }

    /**
     * Create an instance of {@link ESBEntry.RequestOption }
     *
     */
    public ESBEntry.RequestOption createESBEntry1RequestOption() {
        return new ESBEntry.RequestOption();
    }

    /**
     * Create an instance of {@link ESBEntry.MsgInfo.Query }
     *
     */
    public ESBEntry.MsgInfo.Query createESBEntry1MsgInfoQuery() {
        return new ESBEntry.MsgInfo.Query();
    }

}

创建XMLUtil 工具类

package com.comvee.util;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * @program: hismq_fzse
 * @description:
 * @author: wangj
 * @create: 2021/08/12 10:53
 */
public class XMLUtil {

    /**
     *  javabean转xml字符串
     * @param object
     * @return
     * @throws JAXBException
     */
    public  static String javaBeanToXML(Object object) throws JAXBException {
        // JAXB的上下文环境
        JAXBContext context = JAXBContext.newInstance(object.getClass());
        // 创建 Marshaller 实例
        Marshaller marshaller = context.createMarshaller();
        // 设置转换参数 -> 这里举例是告诉序列化器是否格式化输出
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_ENCODING,"UTF-8");
        StringWriter writer = new StringWriter();
        marshaller.marshal(object, writer);
        return writer.toString();
    }

    /**
     * xml字符串转javabean
     * @param xmlStr
     * @param clazz
     * @param <T>
     * @return
     * @throws JAXBException
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static <T> T  XMLToJavaBean(String xmlStr,Class<T> clazz) throws JAXBException, InstantiationException, IllegalAccessException {

        // JAXB的上下文环境
        JAXBContext context = JAXBContext.newInstance(clazz);
        // 创建 UnMarshaller 实例
        Unmarshaller unmarshaller = context.createUnmarshaller();
        return (T)unmarshaller.unmarshal(new StringReader(xmlStr));
    }
}


测试工具类

@SpringBootTest
class HismqFzseApplicationTests {
    @Test
    public void test5() throws JAXBException, InstantiationException, IllegalAccessException {

        // 创建实体类
        ObjectFactory factory = new ObjectFactory();
        ESBEntry eSBEntry = factory.createESBEntry("BS10001");
        List<ESBEntry.MsgInfo.Query> queryList1 = eSBEntry.getMsgInfo().getQuery();
        queryList1.add(ESBEntry.MsgInfo.Query.builder().item("INVALID_FLAG").compy(" = ").value("'333333333'").splice(" and ").build());

        System.out.println(eSBEntry);
        // 实体类转xml
        System.out.println("==================================实体类转xml============================");
        String XML = XMLUtil.javaBeanToXML(eSBEntry);
        System.out.println(XML);

        // xml转bean
        System.out.println("==================================xml转bean============================");
        ESBEntry esbEntry = XMLUtil.XMLToJavaBean(XML,ESBEntry.class);
        System.out.println(esbEntry);
    }
    @Test
    public void test5() throws JAXBException, InstantiationException, IllegalAccessException {

        // 创建实体类
        ObjectFactory factory = new ObjectFactory();
        ESBEntry eSBEntry = factory.createESBEntry("BS10001");
        List<ESBEntry.MsgInfo.Query> queryList1 = eSBEntry.getMsgInfo().getQuery();
        queryList1.add(ESBEntry.MsgInfo.Query.builder().item("INVALID_FLAG").compy(" = ").value("'333333333'").splice(" and ").build());

        System.out.println(eSBEntry);
        // 实体类转xml
        System.out.println("==================================实体类转xml============================");
        String XML = XMLUtil.javaBeanToXML(eSBEntry);
        System.out.println(XML);

        // xml转bean
        System.out.println("==================================xml转bean============================");
        ESBEntry esbEntry = XMLUtil.XMLToJavaBean(XML,ESBEntry.class);
        System.out.println(esbEntry);
    }

}


控制台输出:


ESBEntry(accessControl=ESBEntry.AccessControl(userName=YBF, password=123, sysFlag=1, fid=BS10001), messageHeader=ESBEntry.MessageHeader(fid=BS10001, sourceSysCode=S55, targetSysCode=S02, msgDate=2021-08-15 21:24:53), requestOption=ESBEntry.RequestOption(onceFlag=, startNum=, endNum=), msgInfo=ESBEntry.MsgInfo(msg=, query=[ESBEntry.MsgInfo.Query(item=INVALID_FLAG, compy= = , value='333333333', splice= and )]))
==================================实体类转xml============================
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ESBEntry>
    <AccessControl>
        <UserName>YBF</UserName>
        <Password>123</Password>
        <SysFlag>1</SysFlag>
        <Fid>BS10001</Fid>
    </AccessControl>
    <MessageHeader>
        <Fid>BS10001</Fid>
        <SourceSysCode>S55</SourceSysCode>
        <TargetSysCode>S02</TargetSysCode>
        <MsgDate>2021-08-15 21:24:53</MsgDate>
    </MessageHeader>
    <RequestOption>
        <onceFlag></onceFlag>
        <startNum></startNum>
        <endNum></endNum>
    </RequestOption>
    <MsgInfo>
        <Msg></Msg>
        <query item="INVALID_FLAG" compy=" = " value="'333333333'" splice=" and "/>
    </MsgInfo>
</ESBEntry>

==================================xml转bean============================
ESBEntry(accessControl=ESBEntry.AccessControl(userName=YBF, password=123, sysFlag=1, fid=BS10001), messageHeader=ESBEntry.MessageHeader(fid=BS10001, sourceSysCode=S55, targetSysCode=S02, msgDate=2021-08-15 21:24:53), requestOption=ESBEntry.RequestOption(onceFlag=, startNum=, endNum=), msgInfo=ESBEntry.MsgInfo(msg=, query=[ESBEntry.MsgInfo.Query(item=INVALID_FLAG, compy= = , value='333333333', splice= and )]))

详细使用请查看https://www.w3cschool.cn/jaxb2

上一篇下一篇

猜你喜欢

热点阅读