将 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);  
    }  
}
相关推荐
紫金修道2 小时前
【DeepAgent】概述
开发语言·数据库·python
Via_Neo2 小时前
JAVA中以2为底的对数表示方式
java·开发语言
书到用时方恨少!2 小时前
Python multiprocessing 使用指南:突破 GIL 束缚的并行计算利器
开发语言·python·并行·多进程
cch89182 小时前
PHP五大后台框架横向对比
开发语言·php
天真萌泪3 小时前
JS逆向自用
开发语言·javascript·ecmascript
野生技术架构师3 小时前
一线大厂Java面试八股文全栈通关手册(含源码级详解)
java·开发语言·面试
廋到被风吹走3 小时前
【AI】Codex 多语言实测:Python/Java/JS/SQL 效果横评
java·人工智能·python
Q一件事3 小时前
R语言制图-相关性及关系网络图
开发语言·r语言
tERS ERTS3 小时前
MySQL中查看表结构
java
坊钰3 小时前
Java 死锁问题及其解决方案
java·开发语言·数据库