Java对象转xml(Object to Xml)

时间:2024-04-23 07:11:12

目录

  • 第一章、Java对象转xml
    • 1.1)Java实体类
    • 1.2)Xml中需要包含的字段
    • 1.3)设置根标签和属性序列化方式
    • 1.4)使用JAXBContext和Marshaller进行转换

友情提醒:

先看目录,了解文章结构,点击目录可跳转到文章指定位置。

第一章、Java对象转xml

1.1)Java实体类

这是需要转xml的实体类

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName(value="productionissue")
public class ProductionIssue {

    @TableId(value = "id", type = IdType.AUTO)
    private Integer  id;

    @TableField("userid")
    private String userId;

    @TableField("title")
    private String title;

    @TableField("content")
    private String content;

    @TableField("orderNumber")
    private String orderNumber;

    @TableField("file")
    private byte[] file;

    @TableField("date")
    private String date;

    @TableField("sta")
    private String sta;
}

1.2)Xml中需要包含的字段

因为有些XML字段不在数据库对应的实体类中,所以需要额外建一个XML字段对应的实体类

import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;

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

@Data
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NewInc {

    @XmlElement(name = "WSUSER")
    private String wsUser;

    @XmlElement(name = "WSPASSWORD")
    private String wsPassword;


    @XmlElement(name = "CREATOR")
    private String userId;

    @XmlElement(name = "CREATORCONTACT")
    private String creatorContact;

    @XmlElement(name = "SOURCE")
    private String source;

    @XmlElement(name = "SUMMARY")
    private String title;

    @XmlElement(name = "DESCRIPTION")
    private String content;

    @XmlElement(name = "PRIORITY")
    private String priority;

    @XmlElement(name = "URGENCY")
    private String urgency;

    @XmlElement(name = "REFLECTCANAL")
    private String reflectCanal;

    @XmlElement(name = "HAPPENTIME")
    private String date;

    @XmlElement(name = "ISEFFECTBUSINESS")
    private String isEffectBusiness;

    @XmlElement(name = "ISEFFECTBUSINESS")
    private String effectSituation;

    @XmlElement(name = "ISACCOUNT")
    private String isAccount;

    @XmlElement(name = "ISREGULATOR")
    private String isRegulator;

    @XmlElement(name = "ISBIGCUSTOMER")
    private String isBigCustomer;


}

1.3)设置根标签和属性序列化方式

@XmlRootElement和@XmlAccessorType是JAXB中用于控制Java对象与XML之间映射关系的注解。@XmlRootElement用于指定生成的XML的根标签名,而@XmlAccessorType用于指定属性的序列化方式。


import lombok.Data;
import javax.xml.bind.annotation.*;
import java.util.List;


@Data
@XmlRootElement(name="HAPPY")   //根标签名
@XmlAccessorType(XmlAccessType.FIELD)  //属性序列化
public class NewIncXml {

    @XmlElement(name = "IN")
    private List<NewInc> newIncs;

    public List<NewInc> getNewIncs() {
        return newIncs;
    }

    public void setNewIncs(List<NewInc> newIncs) {
        this.newIncs = newIncs;
    }
}

1.4)使用JAXBContext和Marshaller进行转换

将从数据库中获取的NewInc对象转换为XML格式,并输出每个NewInc对象的XML表示。方便地将Java对象转换为XML数据进行处理或传输。

具体逻辑:
遍历List中的每个NewInc对象:
创建一个新的List对象newIncsOne,并将当前NewInc对象添加到这个List中。
创建一个NewIncXml对象xml,并设置其List newIncs属性为newIncsOne。
创建一个StringWriter对象writer用于将XML数据写入。
使用JAXBContext和Marshaller将NewIncXml对象转换为XML格式,并将结果写入到StringWriter中。
打印输出转换后的XML数据

package com.icbc.coresd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.icbc.coresd.entity.NewInc;
import com.icbc.coresd.entity.NewIncXml;
import com.icbc.coresd.entity.ProductionIssue;
import com.icbc.coresd.mapper.ProductionIssueMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

@Service
public class ProductionIssueServiceImpl {

    @Autowired
    ProductionIssueMapper productionIssueMapper;

    /*
    查询数据库productionissue表数据,设置到NewInc
     */
    public List<NewInc> selectAll() {
       LambdaQueryWrapper<ProductionIssue> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.eq(ProductionIssue::getSta,0 ).select(ProductionIssue::getTitle,ProductionIssue::getDate,ProductionIssue::getContent);

        List<ProductionIssue> productionIssuesList = productionIssueMapper.selectList(queryWrapper);

        List<NewInc> newIncList = new ArrayList<>();
        for (ProductionIssue pi : productionIssuesList) {
            NewInc newInc = new NewInc();
            // 将User的属性映射到Product的属性
            newInc.setUserId(pi.getUserId());
            newInc.setTitle(pi.getTitle());
            newInc.setContent(pi.getContent());
            newInc.setDate(pi.getDate());
            newInc.setWsUser("name");
            newInc.setWsPassword("pass123");
            newInc.setCreatorContact("user@mail");
            newInc.setSource("固定");
            newInc.setPriority("6");
            newInc.setUrgency("02");
            newInc.setReflectCanal("14");
            newInc.setIsEffectBusiness("是");
            newInc.setEffectSituation("file");
            newInc.setIsAccount("否");
            newInc.setIsRegulator("否");
            newInc.setIsBigCustomer("否");

            newIncList.add(newInc);
        }
        return newIncList;
    }


    public void build() {
        List<NewInc> newIncsList = selectAll();

        System.out.println(newIncsList.size());

        for (int i = 0; i < newIncsList.size(); i++) {
            NewInc newInc = newIncsList.get(i);
            // 对取出的数据进行操作
            List<NewInc> newIncsOne = new ArrayList<>();
            newIncsOne.add(newInc);
            NewIncXml xml = new NewIncXml();

            xml.setNewIncs(newIncsOne);

            StringWriter writer = null;
            try {
                JAXBContext context = JAXBContext.newInstance(NewIncXml.class);
                Marshaller marshaller = context.createMarshaller();
                marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                writer = new StringWriter();
                writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
                marshaller.marshal(xml, writer);
            } catch (JAXBException e) {
                e.printStackTrace();
            }

            System.out.println(writer.toString());
        }

    }
}