将 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);  
    }  
}
相关推荐
Aric_Jones38 分钟前
lua入门语法,包含安装,注释,变量,循环等
java·开发语言·git·elasticsearch·junit·lua
Akiiiira38 分钟前
【日撸 Java 三百行】Day 12(顺序表(二))
java·开发语言
EndingCoder1 小时前
2025年JavaScript性能优化全攻略
开发语言·javascript·性能优化
Chase_Mos5 小时前
Spring 必会之微服务篇(1)
java·spring·微服务
码上淘金5 小时前
【Python】Python常用控制结构详解:条件判断、遍历与循环控制
开发语言·python
Brilliant Nemo5 小时前
四、SpringMVC实战:构建高效表述层框架
开发语言·python
格林威7 小时前
Baumer工业相机堡盟工业相机的工业视觉中为什么偏爱“黑白相机”
开发语言·c++·人工智能·数码相机·计算机视觉
小林学习编程7 小时前
SpringBoot校园失物招领信息平台
java·spring boot·后端
撸码到无法自拔7 小时前
docker常见命令
java·spring cloud·docker·容器·eureka
橙子199110167 小时前
在 Kotlin 中什么是委托属性,简要说说其使用场景和原理
android·开发语言·kotlin