将 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);  
    }  
}
相关推荐
Selegant几秒前
Spring Boot 3 + Java 21 全新特性实战:虚拟线程、结构化并发与 Record 类型
java·spring boot·后端
再__努力1点20 分钟前
【68】颜色直方图详解与Python实现
开发语言·图像处理·人工智能·python·算法·计算机视觉
Jinkxs26 分钟前
Java 架构 02:DDD 领域模型设计实战(限界上下文划分)
java·开发语言·架构
百锦再29 分钟前
国产数据库的平替亮点——关系型数据库架构适配
android·java·前端·数据库·sql·算法·数据库架构
爱笑的眼睛1138 分钟前
文本分类的范式演进:从统计概率到语言模型提示工程
java·人工智能·python·ai
毕设源码-钟学长1 小时前
【开题答辩全过程】以 基于PHP的家常菜谱教程网站为例,包含答辩的问题和答案
开发语言·php
周杰伦_Jay1 小时前
【Go/Python/Java】基础语法+核心特性对比
java·python·golang
sszdlbw1 小时前
后端springboot框架入门学习--第一篇
java·spring boot·学习
消失的旧时光-19431 小时前
用 C 实现一个简化版 MessageQueue
c语言·开发语言
小鹿学程序1 小时前
jdk配置完之后java -version还是默认的jdk版本如何更改
java·开发语言·python