将 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);  
    }  
}
相关推荐
2601_95346561几秒前
M3U8 在线播放器:无需安装,一键调试 HLS 直播流
开发语言·前端·javascript·开发工具·m3u8·m3u8在线播放
wechatbot8884 分钟前
企业微信全场景消息发送接口开发实现及接口调用
java·汇编·微信·企业微信
2501_913061347 分钟前
网络原理之HTTP(3)
java·网络·网络协议·http·面试
郭涤生8 分钟前
C++ 线程同步复习
开发语言·c++
Mem0rin10 分钟前
[Java]排序
java·算法·排序算法
Full Stack Developme10 分钟前
Hutool EnumUtil 教程
开发语言·windows·python
番茄去哪了11 分钟前
JeecgBoot框架集成spring ai并进行同步调用异步调用模板
java·人工智能·spring
XMYX-013 分钟前
18 - Go 等待协程:WaitGroup 使用与坑
开发语言·golang
京师20万禁军教头14 分钟前
30面向对象(中级)-super关键字
java
feifeigo12316 分钟前
基于遗传算法的矩形排样MATLAB实现
开发语言·matlab