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);
    }
相关推荐
Resean02232 小时前
架构设计系列(十六):DDD 与代码架构
java·开发语言·架构
学长毕设3 小时前
基于SpringBoot 车辆租赁系统平台-附源码
java·spring boot·后端
feixing_fx4 小时前
解构与展开:可读性和性能的取舍
开发语言·前端·javascript·前端框架
Flynt5 小时前
Spring AI Alibaba 真停更了?我把它的 GitHub 翻了个底朝天
java·spring·开源
前端架构师-老李5 小时前
html教程:header、nav、main、footer 四个标签各管哪一块?
前端·html
烟雨空灵6 小时前
25 天做了个独立开发者作品橱窗,收录 340+ 件作品,代码全开源
前端·node.js
wangruofeng6 小时前
怎么让你的项目更好看?用 UI Lab 练设计原则,给界面去 AI 味
前端·aigc·ai编程
用户69371750013847 小时前
AI 越强,为什么我们反而越来越担心失业?
前端·后端·github
她的男孩8 小时前
Spring Boot 接 Flowable:请假单要同时走财务和行政,包容分支和默认分支怎么配
java·spring boot·工作流引擎
涛涛ing8 小时前
线上突发大面积白屏,排查一天后,我发现是 `JSON.parse` 背了锅
前端