将 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);  
    }  
}
相关推荐
LJianK17 分钟前
线程安全、线程同步、竞态条件
java·开发语言
Ting-yu8 分钟前
SpringCloud快速入门(3)---- 创建微服务项目
java·spring cloud·微服务
tangjunjun-owen18 分钟前
[特殊字符] Python异步调用本地Ollama大模型实战:从Demo到高并发避坑指南
开发语言·chrome·python
RSTJ_162520 分钟前
PYTHON+AI LLM DAY FOURTY-THREE
开发语言·人工智能·python
善恶怪客21 分钟前
Java-二维数组
java
Volunteer Technology21 分钟前
SpringAI(二)Models 模型介绍
开发语言·人工智能·python
勿忘,瞬间25 分钟前
JDBC编程
java
万邦科技Lafite1 小时前
如何通过 item_search_img API 接口获取淘宝商品信息
java·前端·数据库
AKA__Zas1 小时前
芝士算法(双指针篇 1.0)
java·算法·学习方法
lly2024061 小时前
《jEasyUI 取得选中行数据》
开发语言