JAXB解析与生成XML

2024-05-16 13:38
文章标签 xml 生成 解析 jaxb

本文主要是介绍JAXB解析与生成XML,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

使用JAXB可以快速完成Java类到XML的映射,方便XML文件的解析与生成。

常用注解

@ XmlRootElement(name = "Country")
将Java类或枚举类型映射成XML中根元素,设置name属性的值可指定义根元素名称,不设置则默认为类型首字母小写的名称。

@ XmlType(propOrder = {"name", "capital", "population", "foundationTime"})
将Java类后枚举类型映射到XML模式类型,设置propOrder可以指定生成XML中各元素的先后顺序。

@ XmlElement(name = "CFoundationTime")
将JavaBean中的字段值映射到XML元素,设置name属性的值可指定XML元素的名称。

@ XmlAttribute(name = "CRank", required = false)
将JavaBean中的字段映射到XML中元素的属性,设置name属性的值可指定xml中元素属性的名称;
至于required属性,官方文档是说指定 XML 模式属性是可选的还是必需的,不是特别理解。

@ XmlElementWrapper(name = "CountryWrapper")
为集合生成xml包装器元素,简单来讲就是使XML元素更有层次感,更美观,该注解只能用在集合上。


例子

1、类结构如下

Country与Countries为映射对象;
JAXBUtils提供读写XML的方法;
JAXBXMLTest提供读写测试方法;

2、各个类如下

Country类:

package com.jaxb;import javax.xml.bind.annotation.*;@XmlType(propOrder = {"name", "capital", "population", "foundationTime"})
@XmlRootElement(name = "Country")
public class Country {private int population;private String name;private String capital;private int rank;private String foundationTime;public String getFoundationTime() {return foundationTime;}@XmlElement(name = "CFoundationTime")public void setFoundationTime(String foundationTime) {this.foundationTime = foundationTime;}public int getPopulation() {return population;}@XmlElement(name = "CPopulation")public void setPopulation(int population) {this.population = population;}public String getName() {return name;}@XmlElement(name = "CName")public void setName(String name) {this.name = name;}public String getCapital() {return capital;}@XmlElement(name = "CCapital")public void setCapital(String capital) {this.capital = capital;}public int getRank() {return rank;}@XmlAttribute(name = "CRank", required = true)public void setRank(int rank) {this.rank = rank;}@Overridepublic String toString() {return "Country=[Name=" + this.getName() +", Capital=" + this.getCapital() +", Population=" + this.getPopulation() +", FoundationTime=" + this.getFoundationTime() + "]";}
}

Countries类:

package com.jaxb;import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;@XmlRootElement(name = "Countries")
public class Countries {private List<Country> countries;public List<Country> getCountries() {return countries;}@XmlElementWrapper(name = "CountryWrapper")@XmlElement(name = "Country")public void setCountries(List<Country> countries) {this.countries = countries;}@Overridepublic String toString() {return "Countries=[" + this.getCountries() + "]";}
}

JAXBUtils类:

package com.jaxb;import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;public class JAXBUtils {public static void writeXML(Object obj, File path, Class... clazz) throws JAXBException {JAXBContext jctx = JAXBContext.newInstance(clazz);Marshaller marshaller = jctx.createMarshaller();// 格式化输出,设置换行和缩进,不设置则会显示在一行marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);marshaller.marshal(obj, path);// 设置控制台输出marshaller.marshal(obj, System.out);}public static Object readXML(File path, Class... clazz) throws JAXBException {JAXBContext jctx = JAXBContext.newInstance(clazz);Unmarshaller unMarshaller = jctx.createUnmarshaller();Object obj = unMarshaller.unmarshal(path);return obj;}
}

JAXBXMLTest类:

package com.jaxb;import javax.xml.bind.JAXBException;
import java.io.File;
import java.time.LocalDate;
import java.util.ArrayList;public class JAXBXMLTest {private static final String XML_PATH_COUNTRY = "./Country.xml";private static final String XML_PATH_COUNTRIES = "./Countries.xml";public static void main(String[] args) throws JAXBException {Country china = new Country();china.setName("中国");china.setCapital("北京");china.setPopulation(1400000000);china.setRank(25);String fTimeChina = LocalDate.of(1949, 10, 1).toString();china.setFoundationTime(fTimeChina);Country america = new Country();america.setName("United States of America");america.setCapital("New York");america.setPopulation(300000000);america.setRank(11);String fTimeAmerica = LocalDate.of(1776, 7, 4).toString();america.setFoundationTime(fTimeAmerica);File xmlFile = new File(XML_PATH_COUNTRY);File xmlFile1 = new File(XML_PATH_COUNTRIES);System.out.println("\n【写入到" + XML_PATH_COUNTRY + "】");JAXBUtils.writeXML(china, xmlFile, Country.class);System.out.println("\n【写入list到" + XML_PATH_COUNTRIES + "】");Countries countries = new Countries();ArrayList<Country> list = new ArrayList<>();list.add(china);list.add(america);countries.setCountries(list);JAXBUtils.writeXML(countries, xmlFile1, Countries.class);System.out.println("\n【从" + XML_PATH_COUNTRIES + "中读取】");Countries countriesRead = (Countries) JAXBUtils.readXML(xmlFile1, Countries.class, Country.class);System.out.println(countriesRead);System.out.println("\n【从" + XML_PATH_COUNTRY + "中读取】");Country countryRead = (Country) JAXBUtils.readXML(xmlFile, Country.class);System.out.println(countryRead);}
}

运行测试类,结果如下:


这篇关于JAXB解析与生成XML的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/995066

相关文章

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Python包管理工具核心指令uvx举例详细解析

《Python包管理工具核心指令uvx举例详细解析》:本文主要介绍Python包管理工具核心指令uvx的相关资料,uvx是uv工具链中用于临时运行Python命令行工具的高效执行器,依托Rust实... 目录一、uvx 的定位与核心功能二、uvx 的典型应用场景三、uvx 与传统工具对比四、uvx 的技术实

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.

Redis过期删除机制与内存淘汰策略的解析指南

《Redis过期删除机制与内存淘汰策略的解析指南》在使用Redis构建缓存系统时,很多开发者只设置了EXPIRE但却忽略了背后Redis的过期删除机制与内存淘汰策略,下面小编就来和大家详细介绍一下... 目录1、简述2、Redis http://www.chinasem.cn的过期删除策略(Key Expir

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析

《Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析》InstantiationAwareBeanPostProcessor是Spring... 目录一、什么是InstantiationAwareBeanPostProcessor?二、核心方法解

深入解析 Java Future 类及代码示例

《深入解析JavaFuture类及代码示例》JavaFuture是java.util.concurrent包中用于表示异步计算结果的核心接口,下面给大家介绍JavaFuture类及实例代码,感兴... 目录一、Future 类概述二、核心工作机制代码示例执行流程2. 状态机模型3. 核心方法解析行为总结:三

Python实现自动化Word文档样式复制与内容生成

《Python实现自动化Word文档样式复制与内容生成》在办公自动化领域,高效处理Word文档的样式和内容复制是一个常见需求,本文将展示如何利用Python的python-docx库实现... 目录一、为什么需要自动化 Word 文档处理二、核心功能实现:样式与表格的深度复制1. 表格复制(含样式与内容)2