将 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);  
    }  
}
相关推荐
q***92516 分钟前
PHP搭建开发环境(Windows系统)
开发语言·windows·php
Chrison_mu9 分钟前
Android项目背景动效-Kotlin
android·开发语言·kotlin
啃火龙果的兔子10 分钟前
如何控制kotlin项目back的时候,只回退webview的路由
开发语言·kotlin·harmonyos
情怀姑娘12 分钟前
面试题---------------场景+算法
java·算法·mybatis
客梦24 分钟前
Java 学生管理系统
java·笔记
e***09625 分钟前
SpringBoot下获取resources目录下文件的常用方法
java·spring boot·后端
拼好饭和她皆失28 分钟前
C#学习入门
开发语言·学习·c#
q***146429 分钟前
JavaWeb项目打包、部署至Tomcat并启动的全程指南(图文详解)
java·tomcat
分布式存储与RustFS29 分钟前
MinIO 不再“开放”,RustFS 能否成为更优选择?
开发语言·安全·安全架构·企业存储·rustfs
Sunhen_Qiletian31 分钟前
《Python开发之语言基础》第一集:python的语法元素
开发语言·python