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

相关文章

spring中的@MapperScan注解属性解析

《spring中的@MapperScan注解属性解析》@MapperScan是Spring集成MyBatis时自动扫描Mapper接口的注解,简化配置并支持多数据源,通过属性控制扫描路径和过滤条件,利... 目录一、核心功能与作用二、注解属性解析三、底层实现原理四、使用场景与最佳实践五、注意事项与常见问题六

python生成随机唯一id的几种实现方法

《python生成随机唯一id的几种实现方法》在Python中生成随机唯一ID有多种方法,根据不同的需求场景可以选择最适合的方案,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习... 目录方法 1:使用 UUID 模块(推荐)方法 2:使用 Secrets 模块(安全敏感场景)方法

nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析(结合应用场景)

《nginx-t、nginx-sstop和nginx-sreload命令的详细解析(结合应用场景)》本文解析Nginx的-t、-sstop、-sreload命令,分别用于配置语法检... 以下是关于 nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析,结合实际应

MyBatis中$与#的区别解析

《MyBatis中$与#的区别解析》文章浏览阅读314次,点赞4次,收藏6次。MyBatis使用#{}作为参数占位符时,会创建预处理语句(PreparedStatement),并将参数值作为预处理语句... 目录一、介绍二、sql注入风险实例一、介绍#(井号):MyBATis使用#{}作为参数占位符时,会

PostgreSQL的扩展dict_int应用案例解析

《PostgreSQL的扩展dict_int应用案例解析》dict_int扩展为PostgreSQL提供了专业的整数文本处理能力,特别适合需要精确处理数字内容的搜索场景,本文给大家介绍PostgreS... 目录PostgreSQL的扩展dict_int一、扩展概述二、核心功能三、安装与启用四、字典配置方法

深度解析Java DTO(最新推荐)

《深度解析JavaDTO(最新推荐)》DTO(DataTransferObject)是一种用于在不同层(如Controller层、Service层)之间传输数据的对象设计模式,其核心目的是封装数据,... 目录一、什么是DTO?DTO的核心特点:二、为什么需要DTO?(对比Entity)三、实际应用场景解析

深度解析Java项目中包和包之间的联系

《深度解析Java项目中包和包之间的联系》文章浏览阅读850次,点赞13次,收藏8次。本文详细介绍了Java分层架构中的几个关键包:DTO、Controller、Service和Mapper。_jav... 目录前言一、各大包1.DTO1.1、DTO的核心用途1.2. DTO与实体类(Entity)的区别1

Java中的雪花算法Snowflake解析与实践技巧

《Java中的雪花算法Snowflake解析与实践技巧》本文解析了雪花算法的原理、Java实现及生产实践,涵盖ID结构、位运算技巧、时钟回拨处理、WorkerId分配等关键点,并探讨了百度UidGen... 目录一、雪花算法核心原理1.1 算法起源1.2 ID结构详解1.3 核心特性二、Java实现解析2.

python删除xml中的w:ascii属性的步骤

《python删除xml中的w:ascii属性的步骤》使用xml.etree.ElementTree删除WordXML中w:ascii属性,需注册命名空间并定位rFonts元素,通过del操作删除属... 可以使用python的XML.etree.ElementTree模块通过以下步骤删除XML中的w:as

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图