java自带工具对象转xml

java自带工具对象转xml,工具是jaxbContext,不废话,直接上代码

java对象

java 复制代码
package com.configure.util;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlValue;

/**
 * @author A2001111
 * @date 2024/7/5 10:48
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@XmlAccessorType(XmlAccessType.FIELD)
public class UserxxVO {

    @XmlAttribute(name = "name")
    private String userName;

    @XmlValue
    private String password;

}

java对象

java 复制代码
package com.configure.util;

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;
import java.util.List;

/**
 * @author A2001111
 * @date 2024/7/5 11:02
 */
@Data
@XmlRootElement(name = "resource")
@XmlAccessorType(XmlAccessType.FIELD)
public class ResourcexxVO {

    @XmlElement(name = "string")
    private List<UserxxVO> list;

}

生成xml代码

java 复制代码
    public static void main(String[] args) throws JAXBException {
        List<UserxxVO> list = new ArrayList<>();

        for (int i = 0; i < 3; i++) {
            list.add(new UserxxVO("username"+i,"pass1123"));
        }

        ResourcexxVO resourcexxVO = new ResourcexxVO();
        resourcexxVO.setList(list);


        // JAXBContext jaxbContext = JAXBContext.newInstance(UserxxVO.class,ResourcexxVO.class);
        JAXBContext jaxbContext = JAXBContext.newInstance(ResourcexxVO.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT,true);

        StringWriter stringWriter = new StringWriter();
        stringWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        marshaller.marshal(resourcexxVO,stringWriter);
        System.out.println(stringWriter);
    }
相关推荐
快乐点吧5 分钟前
【前端】异步任务风控验证与轮询机制技术方案(通用笔记版)
前端·笔记
pe7er32 分钟前
nuxtjs+git submodule的微前端有没有搞头
前端·设计模式·前端框架
七月的冰红茶40 分钟前
【threejs】第一人称视角之八叉树碰撞检测
前端·threejs
爱掉发的小李1 小时前
前端开发中的输出问题
开发语言·前端·javascript
cainiao0806051 小时前
Java 大视界:基于 Java 的大数据可视化在智慧城市能源消耗动态监测与优化决策中的应用(2025 实战全景)
java
祝余呀1 小时前
HTML初学者第四天
前端·html
长风破浪会有时呀2 小时前
记一次接口优化历程 CountDownLatch
java
云朵大王2 小时前
SQL 视图与事务知识点详解及练习题
java·大数据·数据库
我爱Jack3 小时前
深入解析 LinkedList
java·开发语言
浮桥3 小时前
vue3实现pdf文件预览 - vue-pdf-embed
前端·vue.js·pdf