Application of JAXB---------the mapping (aggregation or combination) of XML to multiple objects and considerations

Source: Internet
Author: User

In our practical applications, the structure of XML is often more than that simple, generally there are 2, 3 layers. That is, if the mapping to an object is an aggregation (a combination).

With the example in our previous chapter, the simple author of our book is now more than a string name, an object author, and contains personal information about the author. So how do we make columns.

Look at the code directly

Package Com.jaxb.first;
Import Javax.xml.bind.annotation.XmlAccessorType;
Import javax.xml.bind.annotation.XmlRootElement;

Import Javax.xml.bind.annotation.XmlType; @XmlRootElement (name = "book")//If you want your can define the order in which the fields are written//Optional @XmlTyp
	E (Proporder = {"Name", "Author", "publisher", "ISBN"}) public class book {private String name;
	Private Author Author;
	Private String publisher;

	Private String ISBN; If you are like the variable name, e.g. ' name ', you can easily change this//name to your xml-output:public String get
	Name () {return name;
	public void SetName (String name) {this.name = name;
	Public Author Getauthor () {return Author;
	public void Setauthor (Author 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 Com.jaxb.first;

Import Javax.xml.bind.annotation.XmlAttribute;

public class Author {

	
	private String name;
	private int age;
	
	@XmlAttribute public
	String GetName () {return
		name;
	}
	public void SetName (String name) {
		this.name = name;
	}
	public int getage () {return age
		;
	}
	public void Setage (int age) {
		this.age = age;
	}
	
	
	
}


Package Com.jaxb.first;

Import java.util.ArrayList;

Import javax.xml.bind.annotation.XmlElement;
Import Javax.xml.bind.annotation.XmlElementWrapper;
Import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement (namespace= "abc") 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;
	}
}


Package Com.jaxb.first;
Import Java.io.FileReader;
Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.io.Writer;

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 Com.sun.xml.bind.marshaller.NamespacePrefixMapper;

	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 Arrayli

		St<book> ();
		Create books Book Book1 = new book ();
		BOOK1.SETISBN ("978-0060554736");
		Book1.setname ("the Game");
		Author a = new Author ();
		A.setage (28);
		A.setname ("Gosling");
		Book1.setauthor (a);
		Book1.setpublisher ("HarperCollins");

		Booklist.add (BOOK1);
		Book Book2 = new book ();
		BOOK2.SETISBN ("978-3832180577");
		Book2.setname ("Feuchtgebiete");
		Author A2 = new Author ();
A2.setage (32);		A2.setname ("James Green");
		Book2.setauthor (A2);
		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 ();
		Namespaceprefixmapper mapper = new Preferredmapper ();

		M.setproperty ("Com.sun.xml.bind.namespacePrefixMapper", mapper);
		M.setproperty (Marshaller.jaxb_formatted_output, boolean.true);

		M.marshal (Bookstore, System.out);
		Writer w = null;
			try {w = new FileWriter (bookstore_xml);
		M.marshal (Bookstore, W);
			Finally {try {w.close ();
		The catch (Exception e) {}}//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));
					for (int i = 0; i < bookstore2.getbookslist (). ToArray (). length; i++) {System.out.println ("book" + (i + 1) + ":"
		+ bookstore2.getbookslist (). Get (i)-getName () + "from" + Bookstore2.getbookslist (). (i). Getauthor ()); The public static class Preferredmapper extends Namespaceprefixmapper {@Override the public String Getpreferredprefix (string NamespaceURI, String suggestion, Boolean Requireprefix)
		{return "pre"; }

		
	}
}


Check out the output:

<?xml version= "1.0" encoding= "UTF-8" standalone= "yes"?> <pre:bookstore "abc" > <bookList>
                <book> <name>the game</name> <author name= "Gosling" >
            <age>28</age> </author> <publisher>Harpercollins</publisher> <isbn>978-0060554736</isbn> </book> <book> &LT;NAME&GT;FEUCHTG ebiete</name> <author name= "James Green" > <age>32</age> &L t;/author> <publisher>dumont buchverlag</publisher> <isbn>978-3832180577</ isbn> </book> </bookList> <location>frankfurt airport</location> &LT;NAME&G T Fraport bookstore</name> </pre:bookstore> Output from We XML file:book 1:the Game from Com.jaxb.first.Aut hor@1774b9b Book 2:feuChtgebiete from com.jaxb.first.author@104c575 


OK is the format we want. Then things will work out.

It is noteworthy that if you want to annotate attributes, you must write the annotation on the property's Get method, as in the case of the @XmlAttribute in our author class, otherwise he will prompt: The same element name XXX.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.