将 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);  
    }  
}
相关推荐
li星野43 分钟前
Qt 单例配置管理器学习记录:JsonConfigManager 的设计原理与使用示例
开发语言·qt·学习
FYKJ_20101 小时前
springboot高校实验室综合管理系统86531-计算机毕业设计、课程设计
java·vue.js·spring boot·后端·python·spring·课程设计
钱栈up2 小时前
AND t.unit_code = 'SM1':一行写死的 SQL 让配料计划页永远拿不到化验值
java·sql·微服务
金銀銅鐵7 小时前
类实例里还有什么——putfield、getfield 与对象传递
java·jvm·后端
默 语8 小时前
HarmonyOS7 事件分发控制(二):onTouchIntercept 镂空玻璃卡——圆内自己接,圆外放行
android·java·开发语言
Amumu121389 小时前
TypeScript学习: 基础知识(二)
开发语言·typescript·ecmascript
sharemylove9 小时前
Java 异常与常用类 学习笔记
java·开发语言·经验分享·笔记·学习
小灰灰搞电子9 小时前
C 语言基础:动态内存管理详解
c语言·开发语言
打工仔折腾 AI10 小时前
L3 静态源码取证|工程评测:python-oracledb 驱动评估中的样本偏差陷阱
开发语言·人工智能·后端·python·性能优化
Amumu1213810 小时前
TypeScript学习: 进阶知识
开发语言·学习·typescript