将 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);  
    }  
}
相关推荐
闲猫5 分钟前
Spring AI / Models / Chat Models / Ollama
java·人工智能·spring
汤米粥21 分钟前
Python爬虫中Xpath用法之——normalize-space()
开发语言·python
FREEDOM_X27 分钟前
Linux 多线程编程——总结
java·linux·运维·ubuntu
科技道人30 分钟前
记录 设置-显示大小和字体
开发语言·android设置·字体和显示大小
tmlx3I08136 分钟前
Tomcat的架构设计和启动过程详解
java·tomcat
浮江雾38 分钟前
Flutter第三节----Dart中的数据类型
android·开发语言·学习·flutter·入门·函数
weixin_4223293143 分钟前
AgentScope Java 项目入门 & Builder 深度解读
java·开发语言·人工智能
shepherd1261 小时前
一次把 Spring MVC 文件上传参数“查没了”的排查:multipart、Filter 与 request body 的连环坑
java·后端·spring·mvc
宠友信息1 小时前
Spring Boot与异步审核构建仿小红书源码内容发布全流程
java·数据库·spring boot·redis·mysql·oracle·uni-app
chh5631 小时前
C++--list
开发语言·数据结构·c++·学习·算法·list