将 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);  
    }  
}
相关推荐
fengfuyao9853 分钟前
C# 高仿QQ截图工具(支持自定义快捷键)
开发语言·c#
2401_857918296 分钟前
C++与自动驾驶系统
开发语言·c++·算法
wenlonglanying7 分钟前
springboot与springcloud对应版本
java·spring boot·spring cloud
稻草猫.13 分钟前
Spring统一功能处理
java·后端·spring
GfovikS0610017 分钟前
C++中的函数式编程
开发语言·c++·算法
2401_8579182918 分钟前
C++中的构建器模式
开发语言·c++·算法
酉鬼女又兒19 分钟前
零基础快速入门前端JavaScript Array 常用方法详解与实战(可用于备赛蓝桥杯Web应用开发)
开发语言·前端·javascript·chrome·蓝桥杯
小罗和阿泽24 分钟前
GUI 自动化测试 pywinauto测试框架
开发语言·python·功能测试·测试工具·pytest
学不完的25 分钟前
ZrLog 博客系统部署指南(无 War 包版,Maven 构建 + 阿里云镜像优化)
java·linux·nginx·阿里云·maven
小杍随笔25 分钟前
【Rust 语言编程知识与应用:元编程详解】
开发语言·后端·rust