将 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);  
    }  
}
相关推荐
Patrick在香港1 分钟前
Python 分析香港 AQHI 归档 1644 天:同一天的空气,早上 8 点报 3,下午 5 点报 10
开发语言·python·数据分析·api·restful·数据可视化·开放数据
重生之小比特2 分钟前
【Java SE】IDEA 调试 Debug 案例完整分析
java·ide·intellij-idea
晴天163 分钟前
JavaScript 与 Java 垃圾回收机制对比
java·开发语言·javascript
金金计较.5 分钟前
Go语言-2
开发语言·算法·golang
3Q工具箱 - BraggTroy13 分钟前
Python + PyInstaller 实战:从零打造 10 个 Windows 桌面小工具(附全部踩坑记录与核心代码)
开发语言·windows·python
xiaohua100913 分钟前
JVM内存优化-jemalloc
java·jvm
吃饱了得干活17 分钟前
Redisson 进阶实战:看门狗机制与分布式锁完全指南
java·redis·后端
淘源码d25 分钟前
基于Java开发的上门家政系统源码,采用SpringBoot+MySQL+UniApp+Vue3技术栈,构建三端一体化平台
java·源码·上门家政·家政系统·同城家政·源码部署
Wang's Blog27 分钟前
Java框架快速入门: Spring Security+OAuth2之多因子认证逻辑与实体类改造
java·开发语言·spring
ashiho30 分钟前
【Spring】RequestParam/PathVariable/RequestBody详解
java·后端·spring·servlet·springmvc