将 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);  
    }  
}
相关推荐
xrandzj37 分钟前
Python面向对象编程入门:类、实例、初始化与封装实践
开发语言·python
DLYSB_2 小时前
API 网关流量洪峰与突发 CC 攻击:我用 Go 写了个“现场物理防御哨兵”,把故障响应压缩到秒级
开发语言·后端·golang·报警灯
markinmarkin2 小时前
Spring 中Bean 的作用域有哪些?
java·后端·spring
山荷枝3 小时前
Java学习第十天
java·学习
matlabgoodboy3 小时前
计算机毕设代做|Java Python Matlab APP 全套开发设计
java·python·课程设计
雨田言炎3 小时前
四、关于Qt项目需要知道的
开发语言·笔记·qt
程序喵大人4 小时前
【C++进阶】STL算法与函数对象 - 02 sort为什么需要随机访问迭代器
开发语言·c++·算法
Source.Liu4 小时前
【Uppsala】入口模块(lib.rs)
xml·rust
SomeB1oody4 小时前
【RustyML入门】2.6. 线性判别分析
开发语言·后端·机器学习·rust·教程
程序员雷欧5 小时前
环形缓冲区深度解析:从基础原理到Disruptor源码的全面剖析
java