Java对象转xml(Object to Xml)


友情提醒:

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

第一章、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());
        }

    }
}

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java对象换为XML格式可以通过Java中的JAXB(Java Architecture for XML Binding)实现。JAXB提供了将Java对象XML之间相互换的功能。 以下是一个简单的Java代码示例,演示如何将Java对象换为XML格式: ```java import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import java.io.StringWriter; public class ObjectToXml { public static void main(String[] args) throws Exception { // 创建一个Person对象 Person person = new Person(); person.setName("张三"); person.setAge(20); // 创建JAXBContext对象 JAXBContext context = JAXBContext.newInstance(Person.class); // 创建Marshaller对象 Marshaller marshaller = context.createMarshaller(); // 设置Marshaller的属性 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 将Java对象换为XML格式 StringWriter writer = new StringWriter(); marshaller.marshal(person, writer); String xml = writer.toString(); System.out.println(xml); } } // 定义一个Person类 import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } ``` 输出结果为: ``` <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <person> <name>张三</name> <age>20</age> </person> ``` 在这个例子中,我们创建了一个Person对象,并使用JAXBContext和Marshaller将其换为XML格式。我们还使用了@XmlRootElement注释来指定根元素的名称。最后,我们将XML字符串打印到控制台上。 注意:在使用JAXB进行对象换时,必须在Java类中使用JAXB注释,以便JAXB可以正确地将Java对象换为XML格式。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值