将 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);  
    }  
}
相关推荐
程序员吕洞宾1 分钟前
开源多维表格SmartTable V1.6.1:工作流画布,让自动化工作流配置更直观、更方便
java·开源·自动化
我登哥MVP7 分钟前
走进 Gang of Four 设计模式:访问者模式
java·设计模式·访问者模式·原型模式
雪碧聊技术9 分钟前
一文深入理解 Java 函数式编程思想
java·函数式编程
AIGS00113 分钟前
突破语义鸿沟:从向量空间JBoltAI看企业大脑构建逻辑
java·大数据·人工智能·人工智能ai大模型应用
琢磨先生David19 分钟前
OpenJDK 与 Oracle JDK 完整区别
java
倔强的石头10623 分钟前
企业智能设备运维管理系统:靠飞算 JavaAI,告别 Java 低效搬砖日常
java
逝水无殇29 分钟前
C# 正则表达式详解
开发语言·后端·正则表达式·c#
深盾科技_Virbox34 分钟前
软件授权工具静默安装实践
java·运维·数据库·安全·软件需求
朱永博42 分钟前
使用Onnruntime实现Padim/Patchcore推理
开发语言·c#
前端H44 分钟前
Biome & Rolldown:Rust 工具链接管前端基建
开发语言·前端·rust