将 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);  
    }  
}
相关推荐
ZeroToOneDev2 分钟前
SpringMvc
java·spring
坚持学习前端日记3 分钟前
认证模块文档
java·服务器·前端·数据库·spring
qq_12498707536 分钟前
基于springboot的文化旅游小程序(源码+论文+部署+安装)
java·spring boot·后端·微信小程序·小程序·毕业设计·旅游
我是一只小青蛙8881 小时前
JavaScript DOM操作全解析
开发语言·javascript·ecmascript
num_killer8 小时前
小白的Langchain学习
java·python·学习·langchain
你怎么知道我是队长9 小时前
C语言---头文件
c语言·开发语言
期待のcode9 小时前
Java虚拟机的运行模式
java·开发语言·jvm
程序员老徐9 小时前
Tomcat源码分析三(Tomcat请求源码分析)
java·tomcat
hqwest9 小时前
码上通QT实战25--报警页面01-报警布局设计
开发语言·qt·qwidget·ui设计·qt布局控件
a程序小傲9 小时前
京东Java面试被问:动态规划的状态压缩和优化技巧
java·开发语言·mysql·算法·adb·postgresql·深度优先