`
cleverGump
  • 浏览: 10749 次
社区版块
存档分类
最新评论

JAXB - Tutorial

    博客分类:
  • Java
阅读更多

转载自: http://www.vogella.com/tutorials/JAXB/article.html

 

JAXB Tutorial. This tutorial give an introduction to Java Architecture for XML Binding (JAXB). This tutorial is based on Java 6.0.

1. Overview

Java Architecture for XML Binding (JAXB) is a Java standard that defines how Java objects are converted from and to XML. It uses a standard set of mappings.

JAXB defines an API for reading and writing Java objects to and from XML documents.

As JAXB is defined via a specification, it is possible to use different implementations for this standard. JAXB defines a service provider which allows the selection of the JAXB implementation.

It applies a lot of defaults thus making reading and writing of XML via Java relatively easy.

 

2. Prerequisitions

The following will demonstrate the JAXB API. For an introduction into using XML with Java please see Java XML tutorial.

3. JAXB 2 - Java Architecture for XML Binding

JAXB uses annotations to indicate the central elements.

Table 1. JAXB annotationsAnnotationDescription

@XmlRootElement(namespace = "namespace")

Define the root element for an XML tree

@XmlType(propOrder = { "field2", "field1",.. })

Allows to define the order in which the fields are written in the XML file

@XmlElement(name = "neuName")

Define the XML element which will be used. Only need to be used if the neuNeu is different then the JavaBeans Name

4. Tutorial: Using JAXB

Create a new Java project called "de.vogella.xml.jaxb". Create the following domain model with the JAXB annotations.

package de.vogella.xml.jaxb.model;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "book")
// If you want you can define the order in which the fields are written
// Optional
@XmlType(propOrder = { "author", "name", "publisher", "isbn" })
public class Book {

        private String name;
        private String author;
        private String publisher;
        private String isbn;

        // If you like the variable name, e.g. "name", you can easily change this
        // name for your XML-Output:
        @XmlElement(name = "title")
        public String getName() {
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }

        public String getAuthor() {
                return author;
        }

        public void setAuthor(String author) {
                this.author = author;
        }

        public String getPublisher() {
                return publisher;
        }

        public void setPublisher(String publisher) {
                this.publisher = publisher;
        }

        public String getIsbn() {
                return isbn;
        }

        public void setIsbn(String isbn) {
                this.isbn = isbn;
        }

}
package de.vogella.xml.jaxb.model;

import java.util.ArrayList;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

//This statement means that class "Bookstore.java" is the root-element of our example
@XmlRootElement(namespace = "de.vogella.xml.jaxb.model")
public class Bookstore {

        // XmLElementWrapper generates a wrapper element around XML representation
        @XmlElementWrapper(name = "bookList")
        // XmlElement sets the name of the entities
        @XmlElement(name = "book")
        private ArrayList<Book> bookList;
        private String name;
        private String location;

        public void setBookList(ArrayList<Book> bookList) {
                this.bookList = bookList;
        }

        public ArrayList<Book> getBooksList() {
                return bookList;
        }

        public String getName() {
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }

        public String getLocation() {
                return location;
        }

        public void setLocation(String location) {
                this.location = location;
        }
}

Create the following test program for writing and reading the XML file.

package test;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import de.vogella.xml.jaxb.model.Book;
import de.vogella.xml.jaxb.model.Bookstore;

public class BookMain {

        private static final String BOOKSTORE_XML = "./bookstore-jaxb.xml";

        public static void main(String[] args) throws JAXBException, IOException {

                ArrayList<Book> bookList = new ArrayList<Book>();

                // create books
                Book book1 = new Book();
                book1.setIsbn("978-0060554736");
                book1.setName("The Game");
                book1.setAuthor("Neil Strauss");
                book1.setPublisher("Harpercollins");
                bookList.add(book1);

                Book book2 = new Book();
                book2.setIsbn("978-3832180577");
                book2.setName("Feuchtgebiete");
                book2.setAuthor("Charlotte Roche");
                book2.setPublisher("Dumont Buchverlag");
                bookList.add(book2);

                // create bookstore, assigning book
                Bookstore bookstore = new Bookstore();
                bookstore.setName("Fraport Bookstore");
                bookstore.setLocation("Frankfurt Airport");
                bookstore.setBookList(bookList);

                // create JAXB context and instantiate marshaller
                JAXBContext context = JAXBContext.newInstance(Bookstore.class);
                Marshaller m = context.createMarshaller();
                m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                // Write to System.out
                m.marshal(bookstore, System.out);

                // Write to File
                m.marshal(bookstore, new File(BOOKSTORE_XML));

                // get variables from our xml file, created before
                System.out.println();
                System.out.println("Output from our XML File: ");
                Unmarshaller um = context.createUnmarshaller();
                Bookstore bookstore2 = (Bookstore) um.unmarshal(new FileReader(
                                BOOKSTORE_XML));
                ArrayList<Book> list = bookstore2.getBooksList();
                for (Book book : list) {
                        System.out.println("Book: " + book.getName() + " from "
                                        + book.getAuthor());
                }
        }
}

If you run the BookMain an XML file will be created from the input objects. Afterwards the file is read again and the objects are re-created based on the XML file.

分享到:
评论

相关推荐

    JAVA-Restful-Service-Tutorial:JAVA Restful 服务教程

    - 使用JAXB或Jackson库将Java对象转换为JSON格式,反之亦然。 - `@XmlRootElement`和`@JsonProperty`注解用于XML和JSON之间的映射。 8. **返回结果**: - `Response`类用于构造HTTP响应,包括状态码、头信息和...

    The Java™ Web Services Tutorial

    它包括了 Java SE 和 Java EE 平台上的一系列工具和库,如 Java API for XML Web Services (JAX-WS), Java API for XML Binding (JAXB) 等,为开发者提供了全面的支持来构建复杂的 Web 服务应用。 #### 三、Java ...

    tutorial-soap-spring-boot-cxf:教程如何使用Spring Boot和Apache CXF创建,测试,部署,监视SOAP-Webservices

    tutorial-soap-spring-boot-cxf 教程如何使用 , 和创建,测试,部署,监视SOAP 接下来的每个步骤都基于前一个步骤。 因此,如果从第3步开始,则代码中将覆盖第1步和第2步。 步骤1-3:随博客文章一起发布: (或...

    The_Java_EE5_Tutorial.rar_Java ee5 CHM_java ee5 tutorial_java e

    8. **Java API for XML Processing (JAXP)** 和 **Java API for XML Binding (JAXB)**:JAXP用于处理XML文档,而JAXB用于将XML数据绑定到Java对象上,反之亦然。 9. **Web Services**:Java EE 5支持SOAP和RESTful...

    J2EE Tutorial 1.4

    4. **JAXB(Java Architecture for XML Binding)**:用于XML和Java对象之间的自动转换,简化了XML处理。 5. **JSTL(JavaServer Pages Standard Tag Library)**:提供了一组标准标签库,提高了JSP的可维护性和...

    JavaEE 5.0 Tutorial.pdf

    - **Java Architecture for XML Binding (JAXB)**:将XML数据绑定到Java对象。 - **SOAP with Attachments API for Java (SAAJ)**:处理SOAP消息。 - **Java API for XML Registries (JAXR)**:查询和注册Web服务。 ...

    Java EE 5.0 教程(chm格式)

    5. **Web服务支持**:Java EE 5.0提供了更全面的Web服务支持,包括JAX-WS(Java API for XML Web Services)和JAXB(Java Architecture for XML Binding),使创建和消费Web服务变得更加简单。 6. **通用日志和审计...

    Oracle Java Tutorial(Oracle Java官方教程, 基于JDK发1.8,CHM格式,全英文)

    甲骨文Java官方教程,涉及Java的各个方面,数据结构,并发,IO,网络,环境,反射,泛型,图形界面,JDBC,JAXB等,层次清晰,案例鲜明。可以在Oracle官网浏览,本资源提供CHM格式便于查阅。

    Addison.Wesley.The.Java.EE.6.Tutorial.Basic.Concepts.4th.Edition.Aug.2010

    8. **WS(Web Services)**:讨论Java EE 6中的Web服务支持,包括JAX-WS(Java API for XML Web Services)和JAXB(Java Architecture for XML Binding),用于创建和消费SOAP服务。 9. **测试与部署**:涵盖单元...

    tutorial-xml:关于处理 XML 文档的 Java 教程的示例文件

    本教程将通过`tutorial-xml-master`这个压缩包中的示例文件,深入探讨如何在Java中解析、创建和操作XML。 1. **解析XML文档** - DOM解析:DOM(Document Object Model)模型将整个XML文档加载到内存中,形成一个树...

    Java and XML

    例如,“The_Java_Web_Services_Tutorial.pdf”可能涵盖了如何使用Java开发和消费Web服务,包括使用JAX-WS(Java API for XML Web Services)创建SOAP服务,以及利用JAXB处理XML数据。 Wiley的“Java Tools Using ...

    jibx 开发指南 Jibx完成Java到XML的相互转换

    与JAXB等其他框架相比,Jibx允许更精细的控制序列化和反序列化过程,比如可以通过XML绑定文件自定义序列化行为。然而,这也意味着使用Jibx需要更多的配置工作,例如生成绑定文件和对应的jar文件。 总结一下,Jibx是...

Global site tag (gtag.js) - Google Analytics