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

相关文章

C#中读取XML文件的四种常用方法

《C#中读取XML文件的四种常用方法》Xml是Internet环境中跨平台的,依赖于内容的技术,是当前处理结构化文档信息的有力工具,下面我们就来看看C#中读取XML文件的方法都有哪些吧... 目录XML简介格式C#读取XML文件方法使用XmlDocument使用XmlTextReader/XmlTextWr

浅析如何使用Swagger生成带权限控制的API文档

《浅析如何使用Swagger生成带权限控制的API文档》当涉及到权限控制时,如何生成既安全又详细的API文档就成了一个关键问题,所以这篇文章小编就来和大家好好聊聊如何用Swagger来生成带有... 目录准备工作配置 Swagger权限控制给 API 加上权限注解查看文档注意事项在咱们的开发工作里,API

C语言中自动与强制转换全解析

《C语言中自动与强制转换全解析》在编写C程序时,类型转换是确保数据正确性和一致性的关键环节,无论是隐式转换还是显式转换,都各有特点和应用场景,本文将详细探讨C语言中的类型转换机制,帮助您更好地理解并在... 目录类型转换的重要性自动类型转换(隐式转换)强制类型转换(显式转换)常见错误与注意事项总结与建议类型

Java使用POI-TL和JFreeChart动态生成Word报告

《Java使用POI-TL和JFreeChart动态生成Word报告》本文介绍了使用POI-TL和JFreeChart生成包含动态数据和图表的Word报告的方法,并分享了实际开发中的踩坑经验,通过代码... 目录前言一、需求背景二、方案分析三、 POI-TL + JFreeChart 实现3.1 Maven

MySQL 缓存机制与架构解析(最新推荐)

《MySQL缓存机制与架构解析(最新推荐)》本文详细介绍了MySQL的缓存机制和整体架构,包括一级缓存(InnoDBBufferPool)和二级缓存(QueryCache),文章还探讨了SQL... 目录一、mysql缓存机制概述二、MySQL整体架构三、SQL查询执行全流程四、MySQL 8.0为何移除查

在Rust中要用Struct和Enum组织数据的原因解析

《在Rust中要用Struct和Enum组织数据的原因解析》在Rust中,Struct和Enum是组织数据的核心工具,Struct用于将相关字段封装为单一实体,便于管理和扩展,Enum用于明确定义所有... 目录为什么在Rust中要用Struct和Enum组织数据?一、使用struct组织数据:将相关字段绑

使用Java实现一个解析CURL脚本小工具

《使用Java实现一个解析CURL脚本小工具》文章介绍了如何使用Java实现一个解析CURL脚本的工具,该工具可以将CURL脚本中的Header解析为KVMap结构,获取URL路径、请求类型,解析UR... 目录使用示例实现原理具体实现CurlParserUtilCurlEntityICurlHandler

深入解析Spring TransactionTemplate 高级用法(示例代码)

《深入解析SpringTransactionTemplate高级用法(示例代码)》TransactionTemplate是Spring框架中一个强大的工具,它允许开发者以编程方式控制事务,通过... 目录1. TransactionTemplate 的核心概念2. 核心接口和类3. TransactionT

数据库使用之union、union all、各种join的用法区别解析

《数据库使用之union、unionall、各种join的用法区别解析》:本文主要介绍SQL中的Union和UnionAll的区别,包括去重与否以及使用时的注意事项,还详细解释了Join关键字,... 目录一、Union 和Union All1、区别:2、注意点:3、具体举例二、Join关键字的区别&php

Spring IOC控制反转的实现解析

《SpringIOC控制反转的实现解析》:本文主要介绍SpringIOC控制反转的实现,IOC是Spring的核心思想之一,它通过将对象的创建、依赖注入和生命周期管理交给容器来实现解耦,使开发者... 目录1. IOC的基本概念1.1 什么是IOC1.2 IOC与DI的关系2. IOC的设计目标3. IOC