将 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);  
    }  
}
相关推荐
only-qi12 小时前
深入理解MySQL中的MVCC:多版本并发控制的实现原理
java·数据库·mysql
爱上妖精的尾巴12 小时前
7-1 WPS JS宏 Object对象创建的几种方法
开发语言·前端·javascript
ZePingPingZe12 小时前
静态代理、JDK和Cglib动态代理、回调
java·开发语言
2501_9216494912 小时前
iTick 全球外汇、股票、期货、基金实时行情 API 接口文档详解
开发语言·python·websocket·金融·restful
万粉变现经纪人12 小时前
如何解决 pip install 代理报错 SOCKS5 握手失败 ReadTimeoutError 问题
java·python·pycharm·beautifulsoup·bug·pandas·pip
你怎么知道我是队长12 小时前
python---进程
开发语言·chrome·python
C++ 老炮儿的技术栈12 小时前
时序数据库 相对于关系型数据库,有什么区别
c语言·开发语言·c++·机器人·时序数据库·visual studio
风月歌12 小时前
2025-2026计算机毕业设计选题指导,java|springboot|ssm项目成品推荐
java·python·小程序·毕业设计·php·源码
heartbeat..12 小时前
Web 状态管理核心技术详解 + JWT 双 Token (Access/Refresh Token) 自动登录
java·网络·jwt·token
Seven9712 小时前
剑指offer-57、二叉树的下一个节点
java