JAXB - Tutorial

阅读更多

转载自: 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 annotations Annotation Description

@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,xml)