将 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);  
    }  
}
相关推荐
安然无虞几秒前
31天Python入门——第20天:魔法方法详解
开发语言·后端·爬虫·python
QQ__17646198244 分钟前
Matlab安装tdms插件
开发语言·matlab·tdms插件
画个逗号给明天"6 分钟前
C#从入门到精通(5)
开发语言·笔记·c#
inxunoffice19 分钟前
导入 Excel 规则批量修改 txt/html/json/xml/csv 等记事本文本文件内容
xml·excel
赤秀30 分钟前
C++模板初阶
开发语言·c++
杉之31 分钟前
Java中的不可变集合
java·笔记·学习
潘多编程34 分钟前
Gradle实战指南:从入门到进阶,与Maven的深度对比
java·maven
故城、36 分钟前
MQ中的RabbitMQ
java·mq
inxunoffice1 小时前
批量删除 txt/html/json/xml/csv 等文本文件空白行
xml