


Detailed introduction to mapping between XML and objects through JAXB
JAXB的全称是Java Architecture for XML Binding,是一项可以通过XML产生Java对象,也可以通过Java对象产生XML的技术。JDK中关于JAXB部分有几个比较重要的接口或类,如:
Ø JAXBContext:它是程序的入口类,提供了XML/Java绑定的操作,包括marshal、unmarshal等。
Ø Marshaller:它负责把Java对象序列化为对应的XML。
Ø Unmarshaller:它负责把XML反序列化为对应的Java对象。
序列化
进行序列化的基本操作步骤如下:
//1、获取一个基于某个class的JAXBContext,即JAXB上下文 JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass()); //2、利用JAXBContext对象创建对象的Marshaller实例。 Marshaller marshaller = jaxbContext.createMarshaller(); //3、设置一些序列化时需要的指定的配置 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); StringWriter writer = new StringWriter(); //4、将对象进行序列化 marshaller.marshal(obj, writer);
1、 创建一个JAXB上下文对象。
2、 利用JAXB上下文对象创建对应的Marshaller对象。
3、 指定序列化时的配置参数,具体可以设置的参数和对应的参数的含义可以参考API文档。
4、 最后一步是将对应的对象序列化到一个Writer、OutputStream、File等输出对象中,具体可以参考Marshaller接口的API文档。
使用JAXB进行对象的序列化时对应的对象类型必须是javax.xml.bind.JAXBElement类型,或者是使用了javax.xml.bind.annotation.XmlRootElement注解标注的类型。XmlRootElement用于标注在class上面,表示把一个class映射为一个XML Element对象。与之相配合使用的注解通常还有XmlElement和XmlAttribute。XmlElement注解用于标注在class的属性上,用于把一个class的属性映射为一个XML Element对象。XmlAttribute注解用于标注在class的属性上,用于把一个class的属性映射为其class对应的XML Element上的一个属性。默认情况下,当我们的一个属性没有使用XmlElement标注时也会被序列化为Xml元素的一个子元素,如果我们不希望Java对象中的某个属性被序列化则可以在对应的属性或对应的get方法上采用XMLTransient进行标注。
示例
Person类
@XmlRootElement public class Person { private Integer id; private String name; private Integer age; private Address address; @XmlAttribute(name = "id") public Integer getId() { returnid; } public void setId(Integer id) { this.id = id; } @XmlAttribute public String getName() { returnname; } public void setName(String name) { this.name = name; } @XmlElement public Integer getAge() { returnage; } public void setAge(Integer age) { this.age = age; } @XmlElement public Address getAddress() { returnaddress; } public void setAddress(Address address) { this.address = address; } }
Address类
@XmlRootElement public class Address { private Integer id; private String province; private String city; private String area; private String other; @XmlAttribute(name="id") public Integer getId() { returnid; } public void setId(Integer id) { this.id = id; } @XmlElement public String getProvince() { returnprovince; } public void setProvince(String province) { this.province = province; } @XmlElement public String getCity() { returncity; } public void setCity(String city) { this.city = city; } @XmlElement public String getArea() { returnarea; } public void setArea(String area) { this.area = area; } @XmlElement public String getOther() { returnother; } public void setOther(String other) { this.other = other; } }
测试方法
@Test public void testMarshal() throws JAXBException { JAXBContext context = JAXBContext.newInstance(Person.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter writer = new StringWriter(); Person person = new Person(); person.setId(1); person.setName("张三"); person.setAge(30); Address address = new Address(); address.setId(1); address.setProvince("广东省"); address.setCity("深圳市"); address.setArea("南山区"); address.setOther("其它"); person.setAddress(address); marshaller.marshal(person, writer); System.out.println(writer.toString()); }
输出结果
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <person id="1" name="张三"> <address id="1"> <area>南山区</area> <city>深圳市</city> <other>其它</other> <province>广东省</province> </address> <age>30</age> </person>
反序列化
进行反序列化的基本步骤如下:
//1、创建一个指定class的JAXB上下文对象 JAXBContext context = JAXBContext.newInstance(Person.class); //2、通过JAXBContext对象创建对应的Unmarshaller对象。 Unmarshaller unmarshaller = context.createUnmarshaller(); File file = new File("D:\\person.xml"); //3、调用Unmarshaller对象的unmarshal方法进行反序列化,接收的参数可以是一个InputStream、Reader、File等 Person person = (Person) unmarshaller.unmarshal(file);
Unmarshaller对象在提供了一系列的unmarshal重载方法,对应的参数类型可以是File、InputStream、Reader等,具体的可以查看对应的API文档。
JAXB工具类
除了使用JAXBContext来创建Marshaller和Unmarshaller对象来实现Java对象和XML之间的互转外,Java还为我们提供了一个工具类JAXB。JAXB工具类提供了一系列的静态方法来简化了Java对象和XML之间的互转,只需要简单的一行代码即可搞定。
@Test public void testMarshal1() { Person person = new Person(); person.setId(1); person.setName("张三"); person.setAge(30); Address address = new Address(); address.setId(1); address.setProvince("广东省"); address.setCity("深圳市"); address.setArea("南山区"); address.setOther("其它"); person.setAddress(address); JAXB.marshal(person, System.out); } @Test public void testUnmarshal1() { File xml = new File("D:\\person.xml"); Person person = JAXB.unmarshal(xml, Person.class); System.out.println(person); }
The above is the detailed content of Detailed introduction to mapping between XML and objects through JAXB. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Implementing filtering and sorting of XML data using Python Introduction: XML is a commonly used data exchange format that stores data in the form of tags and attributes. When processing XML data, we often need to filter and sort the data. Python provides many useful tools and libraries to process XML data. This article will introduce how to use Python to filter and sort XML data. Reading the XML file Before we begin, we need to read the XML file. Python has many XML processing libraries,

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

Using Python to merge and deduplicate XML data XML (eXtensibleMarkupLanguage) is a markup language used to store and transmit data. When processing XML data, sometimes we need to merge multiple XML files into one, or remove duplicate data. This article will introduce how to use Python to implement XML data merging and deduplication, and give corresponding code examples. 1. XML data merging When we have multiple XML files, we need to merge them

Python implements conversion between XML and JSON Introduction: In the daily development process, we often need to convert data between different formats. XML and JSON are common data exchange formats. In Python, we can use various libraries to convert between XML and JSON. This article will introduce several commonly used methods, with code examples. 1. To convert XML to JSON in Python, we can use the xml.etree.ElementTree module

Handling Errors and Exceptions in XML Using Python XML is a commonly used data format used to store and represent structured data. When we use Python to process XML, sometimes we may encounter some errors and exceptions. In this article, I will introduce how to use Python to handle errors and exceptions in XML, and provide some sample code for reference. Use try-except statement to catch XML parsing errors When we use Python to parse XML, sometimes we may encounter some

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

Using Python to implement data validation in XML Introduction: In real life, we often deal with a variety of data, among which XML (Extensible Markup Language) is a commonly used data format. XML has good readability and scalability, and is widely used in various fields, such as data exchange, configuration files, etc. When processing XML data, we often need to verify the data to ensure the integrity and correctness of the data. This article will introduce how to use Python to implement data verification in XML and give the corresponding
