将 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);  
    }  
}
相关推荐
knight_9___3 小时前
RAG面试篇11
java·面试·职场和发展·agent·rag·智能体
Rust研习社3 小时前
Reqwest 兼顾简洁与高性能的现代 HTTP 客户端
开发语言·网络·后端·http·rust
念越3 小时前
Java 文件操作与IO流详解(File类 + 字节流 + 字符流全总结)
java·开发语言·io
派大星酷3 小时前
AOP 完整精讲:原理、核心概念、五种通知、切点语法、自定义注解实战
java·mysql·spring
七颗糖很甜3 小时前
预警!超级厄尔尼诺即将登场:2026-2027年全球气候或迎“极端狂暴模式”
java·大数据·python·算法·github
格林威3 小时前
面阵相机 vs 线阵相机:堡盟与Basler选型差异全解析 + Python实战演示
开发语言·网络·人工智能·python·数码相机·yolo·工业相机
小林望北3 小时前
Kotlin 协程:StateFlow 与 SharedFlow 深度解析
android·开发语言·kotlin
盐烟3 小时前
xpath-csv_doban_slider
开发语言·python
夫礼者3 小时前
【极简监控】挖出被遗忘的 JMX 金矿:用 Jolokia + Hawtio 把 VisualVM 搬进浏览器
java·监控·jolokia·jmx·hawtio
小学生-山海3 小时前
【安卓逆向】WE Learn登录接口iv、pwd参数分析,加密逆向分析
开发语言·python·安卓逆向