将 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);  
    }  
}
相关推荐
chushiyunen3 分钟前
python中的异常处理
开发语言·python
有一个好名字11 分钟前
vibe codeing 开发流程
java
2401_8747325311 分钟前
C++并发编程中的死锁避免
开发语言·c++·算法
2301_7923082513 分钟前
C++编译期数学计算
开发语言·c++·算法
兑生17 分钟前
【灵神题单·贪心】3745. 三元素表达式的最大值 | 排序贪心 | Java
java·开发语言
polaris063022 分钟前
Windows操作系统部署Tomcat详细讲解
java·windows·tomcat
sqyno1sky25 分钟前
C++中的契约编程
开发语言·c++·算法
卓怡学长38 分钟前
m280本科生导师指导平台
java·数据库·spring·tomcat·maven·intellij-idea
python猿39 分钟前
打卡Python王者归来--第30天
开发语言·python
qq_3349031540 分钟前
嵌入式C++驱动开发
开发语言·c++·算法