Java对象转xml(Object to Xml)

ops/2025/2/13 2:20:33/
xmlns="http://www.w3.org/2000/svg" style="display: none;">

目录

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

友情提醒:

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

xml_6">第一章、Java对象转xml

1.1)Java实体类

这是需要转xml的实体类

java">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字段对应的实体类

java">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用于指定属性的序列化方式。

java">
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数据

java">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 {@AutowiredProductionIssueMapper 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());}}
}

http://www.ppmy.cn/ops/7435.html

相关文章

Golang:字符串正则匹配的简单使用

文档 https://golang.google.cn/pkg/regexp/#example_MatchString 方法签名 func MatchString(pattern string, s string) (matched bool, err error)示例 package mainimport ("fmt""regexp" )func main() {matched, err : regexp.MatchString(foo.*,…

Flutter第九弹 构建列表元素间距

目标&#xff1a; 1&#xff09;Flutter Widget组件之间间距怎么表示&#xff1f; 2&#xff09;列表怎么定义子项之间间距&#xff1f; 一、间距的表示组件 列表组件的间距一般采用固定间距&#xff0c;间距占据可见的空间。 已经使用的表示间距的组件 Spacer&#xff1a…

uniapp 页面跳转通信上下级页面互传

第一种 //A页面跳转方法 xx(){uni.navigateTo({url: ./olylis-cascader/demo}); }, //A页面 用来回去B页面返回数据的方法 getValue(list){console.log(list,B页面传递的数据) } ---------------------------------------------------------- B页面 submit(){let pages getCu…

Flink学习(七)-单词统计

前言 Flink是流批一体的框架。因此既可以处理以流的方式处理&#xff0c;也可以按批次处理。 一、代码基础格式 //1st 设置执行环境 xxxEnvironment env xxxEnvironment.getEnvironment;//2nd 设置流 DataSource xxxDSenv.xxxx();//3rd 设置转换 Xxx transformation xxxDS.…

JDK8开始新增的日期和时间

1、为什么要用JDK8开始新增的时间表&#xff1a; 传统的时间类&#xff08;Date&#xff0c;simpleDateFormat&#xff0c;Calender&#xff09;存在如下问题&#xff1a; ①设计不合理&#xff0c;使用不方便&#xff0c;很多都被淘汰了 ②都是可变对象&#xff0c;修改后会…

解决程序化刷新EXCEL提示更新外部链接的弹窗问题

解决方法 【信任中心】-> 【消息栏】->勾选如下策略提示 2. 【信任中心】->【外部内容】->启用下面的三项链接 3. 【信任中心】->【宏设置】->启用所有宏

C++ 随机数

在许多情况下&#xff0c;需要生成随机数。关于随机数生成器&#xff0c;有两个相关的函数。一个是 rand()&#xff0c;该函数只返回一个伪随机数。生成随机数之前必须先调用 srand() 函数。 下面是一个关于生成随机数的简单实例。实例中使用了 time() 函数来获取系统时间的秒…

web安全学习笔记(10)

记一下第十四节课的内容。 一、MySQL学习 数据库基本结构&#xff1a;库——表——列——值 在本地打开navicat&#xff0c;连接数据库&#xff0c;新建一个liuyan库、liuyan库下新建一个member表&#xff1a; 在表里随意添加一些数据&#xff1a; 下面我们学习MySQL查询。新…