将 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);  
    }  
}
相关推荐
无所事事O_o2 分钟前
加密过程及原理浅析
java·加密
05候补工程师6 分钟前
【408 从零到一】线性表逻辑特征、存储结构对比与 C/C++ 动态内存分配避坑指南
c语言·开发语言·数据结构·c++·考研
yongui4783414 分钟前
MATLAB 使用遗传算法求解微电网优化配置数学模型
开发语言·matlab
郝学胜-神的一滴17 分钟前
Python 抽象基类深度解析:从简易模拟到 abc 模块的优雅实践
开发语言·python·pycharm
2301_7717172118 分钟前
最近在刷牛客:使用Spring AOP实现性能监控时
java·后端·spring
Python伍六七29 分钟前
给予Python开发的【16款高效办公自动化工具合集】,告别低效加班!
开发语言·python·自动化
rit843249938 分钟前
基于博弈论的小区分簇算法MATLAB实现
开发语言·算法·matlab
华清远见成都中心40 分钟前
C 语言内存管理深度解析:malloc/free 与嵌入式堆栈分配策略
java·c语言·算法
怕什么真理无穷44 分钟前
C++面试5_ TCP 粘包2(工业级)
开发语言·c++·tcp/ip
qingyulee1 小时前
python redis
开发语言·redis·python