将 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);  
    }  
}
相关推荐
薛定谔的猫喵喵7 小时前
天然气压力能利用系统综合性评价平台:基于Python和PyQt5的AHP与模糊综合评价集成应用
开发语言·python·qt
yuluo_YX7 小时前
Reactive 编程 - Java Reactor
java·python·apache
独好紫罗兰7 小时前
对python的再认识-基于数据结构进行-a004-列表-实用事务
开发语言·数据结构·python
gjxDaniel7 小时前
Objective-C编程语言入门与常见问题
开发语言·objective-c
山岚的运维笔记7 小时前
SQL Server笔记 -- 第20章:TRY/CATCH
java·数据库·笔记·sql·microsoft·sqlserver
choke2337 小时前
[特殊字符] Python异常处理
开发语言·python
云中飞鸿7 小时前
linux中qt安装
开发语言·qt
少控科技7 小时前
QT第6个程序 - 网页内容摘取
开发语言·qt
darkb1rd7 小时前
八、PHP SAPI与运行环境差异
开发语言·网络安全·php·webshell
南极企鹅7 小时前
springBoot项目有几个端口
java·spring boot·后端