将 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);  
    }  
}
相关推荐
祉猷并茂,雯华若锦19 分钟前
Appium 3.x 实战:元素定位与常见错误解析
开发语言·python·appium
名侦探72225 分钟前
构建 Agent 的五大难点与解决方案
java·大数据·人工智能
Demons_kirit28 分钟前
图库原理(以阿里云OSS为案例)
java·阿里云·云计算
SimonKing31 分钟前
那个号称"对标 Spring"的国产框架 Solon,到底行不行?
java·后端·程序员
Lethehong33 分钟前
飞算Java:从需求梳理到风险闭环,搭建云盾企业信息安全与权限管理平台
java·开发语言
霸道流氓气质36 分钟前
SpringBoot中使用字典驱动的动态路由示例
java·spring boot·后端
爱喝水的鱼丶44 分钟前
SAP-ABAP:ALV数据导出增强——实现Excel/PDF/CSV多格式自定义导出
开发语言·性能优化·sap·abap·erp
学计算机的计算基1 小时前
操作系统八股文:进程与线程全面梳理(附调度算法+IPC+锁机制)
java·算法
Mortalbreeze1 小时前
深入理解 Linux 线程机制(四):线程同步——条件变量与信号量
linux·运维·服务器·开发语言·c++
不会c+1 小时前
C语言:入门到精通(408考研版)系列七 派生的数据类型
c语言·开发语言