当前位置: 首页 > article >正文

将 Java 对象自动转换为 XML 字符串

1.创建Java类并使用JAXB注解

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字符串

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);  
    }  
}

http://www.kler.cn/news/324150.html

相关文章:

  • 电子数据交换EDI 835 的处理
  • Spring Boot 进阶- Spring Boot 自定义拦截器详解
  • 中药材识别
  • 前置机、跳板机、堡垒机:安全运维领域的“黄金三角”
  • stm32 FLASH闪存(读写内部FLASH读取芯片ID)
  • Mac下利用vscode配置latex
  • 记一次因视频编码无法在浏览器播放、编码视频报错问题
  • 软件测试学习路线图
  • 【有啥问啥】深度解析迁移学习(Transfer Learning)
  • C#算法(16)—获取上升沿和下降沿信号
  • windows10使用bat脚本安装前后端环境之redis注册服务
  • 微服务--初识MQ
  • 【InsCode AI】Tableau可视化—AI生成
  • 鸿蒙HarmonyOS NEXT系统揭秘:跨端迁移与多端协同
  • 基于Spring框架的分层解耦详解
  • node后端react前端简单实例
  • react hooks--useImperativeHandle
  • 洛谷 P10456 The Pilots Brothers‘ refrigerator
  • 基于php的民宿预订管理系统
  • pkg升级导致xfce虚拟终端无法启动甚至xfce挂死无法登入@FreeBSD(未解决)
  • vue3更具文件目录动态添加路由配置
  • django drf 统一Response格式
  • ES6的简单介绍(第二部分)
  • Unity与AI对话系统互动生成表情示例
  • linux的中断管理机制
  • Python实现Phong着色模型算法
  • sheng的学习笔记-AI-时序差分学习
  • Android——ContentObserver监听短信
  • Mysql高级篇(中)——锁机制
  • 前端测试最强教程 - 实现 fake http 和 fake db