


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!

RSSfeedsuseXMLtosyndicatecontent;parsingtheminvolvesloadingXML,navigatingitsstructure,andextractingdata.Applicationsincludebuildingnewsaggregatorsandtrackingpodcastepisodes.

RSS documents work by publishing content updates through XML files, and users subscribe and receive notifications through RSS readers. 1. Content publisher creates and updates RSS documents. 2. The RSS reader regularly accesses and parses XML files. 3. Users browse and read updated content. Example of usage: Subscribe to TechCrunch's RSS feed, just copy the link to the RSS reader.

The steps to build an RSSfeed using XML are as follows: 1. Create the root element and set the version; 2. Add the channel element and its basic information; 3. Add the entry element, including the title, link and description; 4. Convert the XML structure to a string and output it. With these steps, you can create a valid RSSfeed from scratch and enhance its functionality by adding additional elements such as release date and author information.

The steps to create an RSS document are as follows: 1. Write in XML format, with the root element, including the elements. 2. Add, etc. elements to describe channel information. 3. Add elements, each representing a content entry, including,,,,,,,,,,,. 4. Optionally add and elements to enrich the content. 5. Ensure the XML format is correct, use online tools to verify, optimize performance and keep content updated.

The core role of XML in RSS is to provide a standardized and flexible data format. 1. The structure and markup language characteristics of XML make it suitable for data exchange and storage. 2. RSS uses XML to create a standardized format to facilitate content sharing. 3. The application of XML in RSS includes elements that define feed content, such as title and release date. 4. Advantages include standardization and scalability, and challenges include document verbose and strict syntax requirements. 5. Best practices include validating XML validity, keeping it simple, using CDATA, and regularly updating.

RSSfeedsareXMLdocumentsusedforcontentaggregationanddistribution.Totransformthemintoreadablecontent:1)ParsetheXMLusinglibrarieslikefeedparserinPython.2)HandledifferentRSSversionsandpotentialparsingerrors.3)Transformthedataintouser-friendlyformatsliket

JSONFeed is a JSON-based RSS alternative that has its advantages simplicity and ease of use. 1) JSONFeed uses JSON format, which is easy to generate and parse. 2) It supports dynamic generation and is suitable for modern web development. 3) Using JSONFeed can improve content management efficiency and user experience.

How to build, validate and publish RSSfeeds? 1. Build: Use Python scripts to generate RSSfeed, including title, link, description and release date. 2. Verification: Use FeedValidator.org or Python script to check whether RSSfeed complies with RSS2.0 standards. 3. Publish: Upload RSS files to the server, or use Flask to generate and publish RSSfeed dynamically. Through these steps, you can effectively manage and share content.


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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.