将 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);  
    }  
}
相关推荐
西猫雷婶31 分钟前
python画图|放大和缩小图像
开发语言·python
被二进制支配的打工人33 分钟前
C++ string的基本运用详细解剖
开发语言·数据结构·c++·string
iQM7534 分钟前
Fingerprint.js:精准用户识别的浏览器指纹技术
开发语言·前端·javascript
无尽的大道2 小时前
深入剖析 Android Lifecycle:构建高效稳定的应用
android·java
亚林瓜子3 小时前
使用jaxb来生成多层嵌套xml
xml·jaxb
长天一色3 小时前
【C语言内存管理】第六章 内存对齐
c语言·开发语言
逸狼3 小时前
【JavaEE初阶】文件IO(下)
java·java-ee
向宇it3 小时前
fastadmin搜索刷新列表,怎么限制用户频繁点击?
开发语言·前端·javascript·fastadmin
Ylucius4 小时前
常见服务器大全----都是什么?又有何作用?区别联系是什么?---web,应用,数据库,文件,消息队列服务器,Tomat,Nginx,vite.....
java·前端·javascript·chrome·学习·node.js·express