将 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);  
    }  
}
相关推荐
肉肉不想干后端19 小时前
联合订单并发退款:一次分布式锁冲突的排查与思考
java
用户47451894751019 小时前
全链路日志追踪利器:trace-spring-boot-starter 实战指南
java
acx匿19 小时前
【Windows10 下 JDK17 环境变量配置超详细教程(ZIP 版)】
java·jdk
Renhao-Wan19 小时前
Java 算法实践(七):动态规划
java·算法·动态规划
新缸中之脑19 小时前
Sonnet 4.6 vs Opus 4.6
java·开发语言
曹牧19 小时前
Java:@RequestBody 和 @RequestParam混合使用
java·开发语言
甲枫叶20 小时前
【claude+weelinking产品经理系列16】数据可视化——用图表讲述产品数据的故事
java·人工智能·python·信息可视化·产品经理·ai编程
思茂信息20 小时前
基于CST 3D Combined功能的以太网口RE仿真
开发语言·javascript·单片机·嵌入式硬件·matlab·3d
番茄去哪了20 小时前
Python基础入门(二)
linux·服务器·开发语言·python
代龙涛20 小时前
wordpress块主题
开发语言·后端·php