使用JDK自带的JAXB进行实体类与XML的相互转换工具类

以公众号回复消息的格式转换xml

使用JDK自带的JAXB进行实体类与XML的相互转换工具类

新建实体类

这里需要注意几个注解

  • @XmlRootElement(name = "根节点名字")
  • @XmlElement(name = "节点名称大写小写均可在此定义")
  • @XmlTransient 注解解决 JavaBean 属性名称与字段名称之间的名称冲突,或者用于防止字段/属性的映射
  • @XmlElementWrapper(name = "节点名")//使用list数组需要使用该注解,使下一级嵌套在该数组下
    private List articles;

BaseMessage类


import lombok.Data;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import java.util.Map;

/**
 * @PackageName : com.rzk.pojo
 * @FileName : BaseMessage
 * @Description : 父类消息体
 * @Author : rzk
 * @CreateTime : 19/1/2022 上午2:08
 * @Version : v1.0
 */
@Data
public class BaseMessage {
    @XmlElement(name = "ToUserName")
    private String toUserName;
    @XmlElement(name = "FromUserName")
    private String fromUserName;
    @XmlElement(name = "CreateTime")
    private String createTime;
    @XmlElement(name = "MsgType")
    private String msgType;

    public BaseMessage() {
    }

    public BaseMessage(Map<String,String> requestMap) {
        this.toUserName = requestMap.get("ToUserName");
        this.fromUserName = requestMap.get("FromUserName");
        this.createTime = System.currentTimeMillis()/1000+"";
    }

    public String getToUserName() {
        return toUserName;
    }
    @XmlTransient
    public void setToUserName(String toUserName) {
        this.toUserName = toUserName;
    }

    public String getFromUserName() {
        return fromUserName;
    }
    @XmlTransient
    public void setFromUserName(String fromUserName) {
        this.fromUserName = fromUserName;
    }

    public String getCreateTime() {
        return createTime;
    }
    @XmlTransient
    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    public String getMsgType() {
        return msgType;
    }
    @XmlTransient
    public void setMsgType(String msgType) {
        this.msgType = msgType;
    }
}

NewsInfoMessage 类 包含Articles数组

import javax.xml.bind.annotation.*;
import java.util.List;
import java.util.Map;

/**
 * @PackageName : com.rzk.pojo
 * @FileName : NewsInfoMessage
 * @Description :
 * @Author : rzk
 * @CreateTime : 24/1/2022 上午1:03
 * @Version : v1.0
 */
@XmlRootElement(name = "xml")
public class NewsInfoMessage extends BaseMessage {
    @XmlElement(name = "ArticleCount")
    private String articleCount;
    @XmlElement(name = "Articles")
    @XmlElementWrapper(name = "Articles")//使用list数组需要使用该注解,使下一级嵌套在该数组下
    private List<Articles> articles;

    public NewsInfoMessage() {
    }

    public NewsInfoMessage(Map<String, String> requestMap, String articleCount, List<Articles> articles) {
        super(requestMap);
        setMsgType("news");
        this.articleCount = articleCount;
        this.articles = articles;
    }

    public String getArticleCount() {
        return articleCount;
    }
    @XmlTransient
    public void setArticleCount(String articleCount) {
        this.articleCount = articleCount;
    }

    public List<Articles> getArticles() {
        return articles;
    }
    @XmlTransient
    public void setArticles(List<Articles> articles) {
        this.articles = articles;
    }

    @Override
    public String toString() {
        return "NewsInfoMessage{" +
                "articleCount='" + articleCount + '\'' +
                ", articles=" + articles +
                '}';
    }
}

Articles 类 包含Item

public class Articles {

    @XmlElement(name = "Item")
    private Item item;

    public Articles(Item item) {
        this.item = item;
    }

    public Articles() {
    }

    public Item getItem() {
        return item;
    }

    @XmlTransient
    public void setItem(Item item) {
        this.item = item;
    }

    @Override
    public String toString() {
        return "Articles{" +
                "item=" + item +
                '}';
    }
}

Item 类


import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;

/**
 * @PackageName : com.rzk.pojo
 * @FileName : Item
 * @Description :
 * @Author : rzk
 * @CreateTime : 24/1/2022 上午1:13
 * @Version : v1.0
 */
public class Item {
    @XmlElement(name = "title")
    private String title;
    @XmlElement(name = "Description")
    private String description;
    @XmlElement(name = "PicUrl")
    private String picUrl;
    @XmlElement(name = "Url")
    private String url;

    public Item() {
    }

    public Item(String title, String description, String picUrl, String url) {
        this.title = title;
        this.description = description;
        this.picUrl = picUrl;
        this.url = url;
    }

    public String getTitle() {
        return title;
    }

    @XmlTransient
    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }
    @XmlTransient
    public void setDescription(String description) {
        this.description = description;
    }

    public String getPicUrl() {
        return picUrl;
    }
    @XmlTransient
    public void setPicUrl(String picUrl) {
        this.picUrl = picUrl;
    }

    public String getUrl() {
        return url;
    }
    @XmlTransient
    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public String toString() {
        return "Item{" +
                "title='" + title + '\'' +
                ", description='" + description + '\'' +
                ", picUrl='" + picUrl + '\'' +
                ", url='" + url + '\'' +
                '}';
    }
}

工具类

    /**
     * 对象转XML
     * @param obj 目标对象
     * @return  返回string格式的xml报文
     */
    public static String objToXml(Object obj){
        StringWriter sw = new StringWriter();
        String result = null;
        try {
            //通过传入的类,创建该类的转换上下文
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            //创建实例
            Marshaller marshaller = context.createMarshaller();
            //格式化xml输出的格式,true会格式化输出,false会全部压缩到一起=
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
            //是否打印xml的说明头 <?xml version="1.0" encoding="UTF-8" standalone="yes">
            //设置为true表示不打印,设置为false表示打印,默认打印
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT,Boolean.FALSE);
            //将对象转换成输出流形式的xml
            marshaller.marshal(obj,sw);
            result = sw.toString() ;
        } catch (JAXBException e) {
            logger.error("对象转XML异常:{}",e.getMessage());
            e.printStackTrace();
        }finally {
            try {
                sw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

测试

    @Test
    void xmlTest() throws JAXBException {
        Map<String,String> map = new HashMap<>();
        ArrayList<Articles> arrayList = new ArrayList<>();
        Articles articles = new Articles();
        map.put("ToUserName","to");
        map.put("FromUserName","from");
        map.put("MsgType","type");


        Item item1 = new Item("英语", "1", "http://", "http://");
        Item item2 = new Item("数学", "2", "http://", "http://");
        Item item3 = new Item("政治", "3", "http://", "http://");
        articles.setItem(item1);
        articles.setItem(item2);
        articles.setItem(item3);
        arrayList.add(articles);
        NewsInfoMessage msg = new NewsInfoMessage(map,"1",arrayList);
        System.out.println("打印iTem===>{}"+msg );
        System.out.println("打印iTem===>{}"+BeanToXml.convertToXml(msg ));

    }

打印结果

打印iTem===>{}NewsInfoMessage{articleCount='1', articles=[Articles{item=Item{title='政治', description='3', picUrl='http://', url='http://'}}]}
打印iTem===>{}<xml>
    <ToUserName>to</ToUserName>
    <FromUserName>from</FromUserName>
    <CreateTime>1643046829</CreateTime>
    <MsgType>news</MsgType>
    <ArticleCount>1</ArticleCount>
    <Articles>
        <Articles>
            <Item>
                <title>政治</title>
                <Description>3</Description>
                <PicUrl>http://</PicUrl>
                <Url>http://</Url>
            </Item>
        </Articles>
    </Articles>
</xml>
上一篇:for_in循环


下一篇:vue中的循环语法(v-for)