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

相关文章

Mysql中设计数据表的过程解析

《Mysql中设计数据表的过程解析》数据库约束通过NOTNULL、UNIQUE、DEFAULT、主键和外键等规则保障数据完整性,自动校验数据,减少人工错误,提升数据一致性和业务逻辑严谨性,本文介绍My... 目录1.引言2.NOT NULL——制定某列不可以存储NULL值2.UNIQUE——保证某一列的每一

深度解析Nginx日志分析与499状态码问题解决

《深度解析Nginx日志分析与499状态码问题解决》在Web服务器运维和性能优化过程中,Nginx日志是排查问题的重要依据,本文将围绕Nginx日志分析、499状态码的成因、排查方法及解决方案展开讨论... 目录前言1. Nginx日志基础1.1 Nginx日志存放位置1.2 Nginx日志格式2. 499

MySQL CTE (Common Table Expressions)示例全解析

《MySQLCTE(CommonTableExpressions)示例全解析》MySQL8.0引入CTE,支持递归查询,可创建临时命名结果集,提升复杂查询的可读性与维护性,适用于层次结构数据处... 目录基本语法CTE 主要特点非递归 CTE简单 CTE 示例多 CTE 示例递归 CTE基本递归 CTE 结

Spring Boot 3.x 中 WebClient 示例详解析

《SpringBoot3.x中WebClient示例详解析》SpringBoot3.x中WebClient是响应式HTTP客户端,替代RestTemplate,支持异步非阻塞请求,涵盖GET... 目录Spring Boot 3.x 中 WebClient 全面详解及示例1. WebClient 简介2.

在MySQL中实现冷热数据分离的方法及使用场景底层原理解析

《在MySQL中实现冷热数据分离的方法及使用场景底层原理解析》MySQL冷热数据分离通过分表/分区策略、数据归档和索引优化,将频繁访问的热数据与冷数据分开存储,提升查询效率并降低存储成本,适用于高并发... 目录实现冷热数据分离1. 分表策略2. 使用分区表3. 数据归档与迁移在mysql中实现冷热数据分

C#解析JSON数据全攻略指南

《C#解析JSON数据全攻略指南》这篇文章主要为大家详细介绍了使用C#解析JSON数据全攻略指南,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、为什么jsON是C#开发必修课?二、四步搞定网络JSON数据1. 获取数据 - HttpClient最佳实践2. 动态解析 - 快速

Spring Boot3.0新特性全面解析与应用实战

《SpringBoot3.0新特性全面解析与应用实战》SpringBoot3.0作为Spring生态系统的一个重要里程碑,带来了众多令人兴奋的新特性和改进,本文将深入解析SpringBoot3.0的... 目录核心变化概览Java版本要求提升迁移至Jakarta EE重要新特性详解1. Native Ima

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 命令的详细解析,结合实际应