将 Java 对象自动转换为 XML 字符串

1.创建Java类并使用JAXB注解

java 复制代码
import javax.xml.bind.annotation.XmlRootElement;  
import javax.xml.bind.annotation.XmlElement;  

@XmlRootElement  
public class Customer {  
    private String name;  
    private int age;  

    // JAXB要求有一个无参构造函数  
    public Customer() {  
    }  

    // 构造函数、getter和setter略  

    @XmlElement  
    public String getName() {  
        return name;  
    }  

    public void setName(String name) {  
        this.name = name;  
    }  

    @XmlElement  
    public int getAge() {  
        return age;  
    }  

    public void setAge(int age) {  
        this.age = age;  
    }  
}

2.将Java对象转换为XML字符串

java 复制代码
import javax.xml.bind.JAXBContext;  
import javax.xml.bind.Marshaller;  
import java.io.StringWriter;  

public class JAXBExample {  
    public static void main(String[] args) throws Exception {  
        Customer customer = new Customer();  
        customer.setName("John Doe");  
        customer.setAge(30);  

        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);  

        Marshaller marshaller = jaxbContext.createMarshaller();  
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  

        StringWriter writer = new StringWriter();  
        marshaller.marshal(customer, writer);  

        String xmlString = writer.toString();  
        System.out.println(xmlString);  
    }  
}
相关推荐
武昌库里写JAVA3 小时前
SpringBoot+Vue 项目介绍
java·javascript·git·sql·ai
学长毕设4 小时前
基于SpringBoot的儿童慈善捐赠管理系统-附源码
java·spring boot·后端
慧一居士4 小时前
@RestControllerAdvice 的注解作用和使用
java
ComPDFKit5 小时前
RAG 回答只显示 PDF 文件名?用 Python 保留引用页码
开发语言·python·pdf·rag
FRing035 小时前
vue3干货总结2(vue3生命周期、父子通信、模版引用、provide和inject)
开发语言·前端·vue.js·vue3
学长毕设5 小时前
基于SpringBoot非遗文化展示与传播平台设计与实现-附源码
java·spring boot·后端
金銀銅鐵7 小时前
用 Swing 重做操作数栈演示
java·jvm·后端
琳少_7 小时前
java程序开发笔记
java·开发语言·数据库·笔记
七夜zippoe7 小时前
Agent 告警设计:分级告警、智能降噪与值班排班
开发语言·ai·agent·告警·智能降噪·值班排班
叼烟扛炮9 小时前
[LangChain] 学习笔记(15):为什么你的重试没用——429、抖动、fallback 与熔断
java·服务器·前端