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);
    }
相关推荐
间彧14 分钟前
Spring Boot集成Spring Security 6.x完整指南
java
这里有鱼汤15 分钟前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
用户214118326360244 分钟前
dify案例分享-免费玩转 AI 绘图!Dify 整合 Qwen-Image,文生图 图生图一步到位
前端
IT_陈寒1 小时前
Redis 性能翻倍的 7 个冷门技巧,第 5 个大多数人都不知道!
前端·人工智能·后端
xiezhr1 小时前
用户只需要知道「怎么办」,不需要知道「为什么炸了」
java·api·接口设计规范
xiezhr1 小时前
接口设计18条军规:写给那些半夜被“502”叫醒的人
java·api·restful
mCell8 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip8 小时前
Node.js 子进程:child_process
前端·javascript
RainbowSea10 小时前
12. LangChain4j + 向量数据库操作详细说明
java·langchain·ai编程
RainbowSea10 小时前
11. LangChain4j + Tools(Function Calling)的使用详细说明
java·langchain·ai编程