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);
    }
相关推荐
web安全工具库3 分钟前
Linux 高手进阶:Vim 核心模式与分屏操作详解
linux·运维·服务器·前端·数据库
huohaiyu5 分钟前
synchronized (Java)
java·开发语言·安全·synchronized
梵得儿SHI5 分钟前
Java 工具类详解:Arrays、Collections、Objects 一篇通关
java·工具类·collections·arrays·objects
一枚前端小能手8 分钟前
🔥 SSR服务端渲染实战技巧 - 从零到一构建高性能全栈应用
前端·javascript
Komorebi_99998 分钟前
Vue3 provide/inject 详细组件关系说明
前端·javascript·vue.js
熊小猿13 分钟前
Spring Boot 的 7 大核心优势
java·spring boot·后端
摸鱼的老谭15 分钟前
Java学习之旅第二季-13:方法重写
java·学习·方法重写
云灬沙15 分钟前
IDEA2025无法更新使用Terminal控制台
java·intellij-idea·idea·intellij idea
Yield & Allure16 分钟前
IDEA在plugins里搜不到mybatisx插件的解决方法
java·ide·intellij-idea
yunmi_20 分钟前
安全框架 SpringSecurity 入门(超详细,IDEA2024)
java·spring boot·spring·junit·maven·mybatis·spring security