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);
    }
相关推荐
想学后端的前端工程师11 小时前
【微前端架构实战指南:从原理到落地】
前端·架构·状态模式
Jerry404_NotFound11 小时前
工厂方法模式
java·开发语言·jvm·工厂方法模式
一起养小猫11 小时前
【探索实战】Kurator统一流量治理深度实践:基于Istio的跨集群服务网格
java·云原生·istio
微风欲寻竹影11 小时前
深入理解Java中的String
java·开发语言
Coder_Boy_11 小时前
基于SpringAI的智能平台基座开发-(二)
java·人工智能·springboot·aiops·langchain4j
代码or搬砖11 小时前
TransactionManager 详解、常见问题、解决方法
java·开发语言·spring
Keya11 小时前
DevEco Studio 使用技巧全面解析
前端·前端框架·harmonyos
_Rookie._12 小时前
web请求 错误拦截
前端
廋到被风吹走12 小时前
【Spring】Spring Context 详细介绍
java·后端·spring
青鸟北大也是北大12 小时前
CSS单位与字体样式全解析
前端·css·html