将 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);  
    }  
}
相关推荐
毕设源码-赖学姐3 分钟前
【开题答辩全过程】以 网络药店管理系统为例,包含答辩的问题和答案
java·eclipse
努力也学不会java4 分钟前
【Java并发】揭秘Lock体系 -- 深入理解ReentrantReadWriteLock
java·开发语言·python·机器学习
埃泽漫笔17 分钟前
消息队列延迟与过期问题的实战解决
java·mq
vxtkjzxt88817 分钟前
自动化脚本矩阵运营
开发语言·php
王严培.27 分钟前
7.MATLAB疑难问题诊疗的技术
开发语言·matlab·信息可视化
花花无缺35 分钟前
资源泄露问题
java·后端·http
wjs202438 分钟前
PHP MySQL 使用 ORDER BY 排序查询
开发语言
爱敲代码的TOM44 分钟前
深入剖析Java通信架构下的三种IO模式2
java·开发语言·架构
杨DaB1 小时前
【JavaSE】JVM
java·jvm
lang201509281 小时前
掌握MyBatis Java API:高效操作数据库
java·数据库·mybatis