将 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);  
    }  
}
相关推荐
瓦特what?11 分钟前
关于C++的#include的超超超详细讲解
java·开发语言·数据结构·c++·算法·信息可视化·数据挖掘
祁同伟.44 分钟前
【C++】动态内存管理
开发语言·c++
是乐谷1 小时前
阿里云杭州 AI 产品法务岗位信息分享(2025 年 8 月)
java·人工智能·阿里云·面试·职场和发展·机器人·云计算
一只鲲1 小时前
40 C++ STL模板库9-容器2-vector
开发语言·c++
励志不掉头发的内向程序员1 小时前
C++基础——内存管理
开发语言·c++
Java水解1 小时前
Java中的四种引用类型详解:强引用、软引用、弱引用和虚引用
java·后端
lifallen1 小时前
JCTools 无锁并发队列基础:ConcurrentCircularArrayQueue
java·开发语言·数据结构·算法
一叶飘零_sweeeet1 小时前
IDEA 插件 Trae AI 全攻略
java·人工智能·intellij-idea
千里镜宵烛2 小时前
深入理解 Linux 线程:从概念到虚拟地址空间的全面解析
开发语言·c++·操作系统·线程
欧哈东哥2 小时前
【C++】标准库中用于组合多个值的数据结构pair、tuple、array...
java·数据结构·c++