将 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);  
    }  
}
相关推荐
z落落14 小时前
C# 索引器 this[]
开发语言·c#
csdn_aspnet14 小时前
C# List 移除某个属性值中最大的值
开发语言·c#·list
2601_9611940214 小时前
2026六级词汇资料电子版|大学英语六级核心词汇PDF
java·spring·eclipse·pdf·tomcat·hibernate
xindon1214 小时前
go语言项目部署的makefile
开发语言·后端·golang
布朗克16814 小时前
18 面向对象综合实战——设计一个图书管理系统
java·面试·职场和发展·面向对象实战
老毛肚14 小时前
记一次逆向
开发语言·python
凯瑟琳.奥古斯特14 小时前
力扣1002题C++解法详解
开发语言·c++·算法·leetcode·职场和发展
钟灵92114 小时前
C++【模板初阶】
开发语言·c++·笔记·c#
码不停蹄的玄黓14 小时前
旁路缓存(Cache-Aside,CA)
java·开发语言