将 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);  
    }  
}
相关推荐
__万波__1 分钟前
二十三种设计模式(二)--工厂方法模式
java·设计模式·工厂方法模式
o***36935 分钟前
python爬虫——爬取全年天气数据并做可视化分析
开发语言·爬虫·python
汤姆yu5 分钟前
基于SpringBoot的餐饮财务管理系统的设计与实现
java·spring boot·后端
枫叶丹413 分钟前
【Qt开发】Qt窗口(三) -> QStatusBar状态栏
c语言·开发语言·数据库·c++·qt·microsoft
亮子AI15 分钟前
【JavaScript】修改数组的正确方法
开发语言·javascript·ecmascript
q***311425 分钟前
【JAVA进阶篇教学】第十二篇:Java中ReentrantReadWriteLock锁讲解
java·数据库·python
带刺的坐椅26 分钟前
Solon AI 开发学习8 - chat - Vision(理解)图片、声音、视频
java·ai·solon·mcp
浮尘笔记31 分钟前
Go语言中如何实现线程安全的map
开发语言·后端·安全·golang