XML与javabean互转

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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,922评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,591评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,546评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,467评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,553评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,580评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,588评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,334评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,780评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,092评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,270评论 1 344
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,925评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,573评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,194评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,437评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,154评论 2 366
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,127评论 2 352

推荐阅读更多精彩内容