JAXB implements conversion between Java objects and XML

Source: Internet
Author: User

First, familiarize yourself with some of the annotations commonly used by JAXB to implement the object and XML for mutual transfer:

[email protected], for class-level annotations, corresponding to the XML element. The name of the root node is defined by the Name property.

[email protected], defining what types of mappings in this class need to be mapped to XML. (If @xmlaccessortype is not present, xmlaccesstype.public_member annotations are used by default)

Parameters: XmlAccessType.FIELD:java All member variables in the object.

All member variables in the XmlAccessType.PROPERTY:java object that are accessed through Getter/setter mode.

A member variable of all public access rights in the XmlAccessType.PUBLIC_MEMBER:java object and a member variable accessed through Getter/setter mode.

All properties of the XmlAccessType.NONE:java object are not mapped to elements of XML.

[email protected], used to map the properties of a Java object to an XML attribute, and to specify an alias for the generated XML property through the Name property.

[Email protected], specify a field or Get/set method to map to the node of the XML. The name of the root node is defined by the Name property.

[email protected], which defines a parent node for an array or collection. The name of the parent node is defined by the Name property.

Let's look at an example:

First define a student class, student as follows:

1 packageCom.quest.software.bus4j.ui.framework.extend.frameParase.test; 2 3 ImportJava.util.List; 4 5 ImportJavax.xml.bind.annotation.XmlAttribute; 6 ImportJavax.xml.bind.annotation.XmlElement; 7 ImportJavax.xml.bind.annotation.XmlElementWrapper; 8 9 public classStudent {ten string name;//name one string sex;//gender int number;//study No. String className;//class list<string> hobby; /HobbiesStudent () {17}18 public Student (String name,string sex,intnumber,19 String classname,list<string>Hobby) {this.name =Name;21 This.sex =Sex;22 This.number =number;23 This.classname =Classname;24 This.hobby =Hobby;25}26 @XmlAttribute (name= "name") PublicString GetName () {-ReturnName;29}30 public voidSetName (String name) {this.name =Name;32}33 @XmlAttribute (name= "Sex") PublicString Getsex () {return sex;37 }38 public void  setsex (String sex) {this.sex =  sex;40 }41 @XmlAttribute (name = "number" ) number;45 public int  GetNumber () {] return  }46 public void setnumber (int  num ber) {this.number =  number;48 }49 @XmlElement (name= "ClassName" ) public  String Getclassna Me () { classname;53 }54 public void  setclassname (String className) {this.classname =  classname;56 }57 @XmlElementWrapper (name= "Hobbys" ) @XmlElement (name = "Hobby" ) public List <string>  gethobby () { hobby;62 }63 public void Sethobby (LIST<STRING>  Hobby {this.hobby =  hobby;65 }66}           

Remember, if the Java object Properties add both the get and set methods, the annotations cannot be defined on the attribute definition, only one can be defined on the Get or set method, or JAXB will error!! As follows:

Exception in thread "main" com.sun.xml.internal.bind.v2.runtime.illegalannotationsexception:1 counts of Illegalannotationexceptions
Class has both properties of the same name "name"

Then define the Student collection class, studentlist as follows:

1 package com.quest.software.bus4j.ui.framework.extend.frameParase.test; 2  3 import java.util.List; 4  5 Import javax.xml.bind.annotation.XmlElement; 6 import javax.xml.bind.annotation.XmlRootElement; 7  8 @XmlRootElement (name= "List") 9 public class Studentlist {ten list<student> students;// A collection of all student information @XmlElement (name = "Student"), publiclist<student> getstudents () {return }17 p ublic void Setstudents (list<student> students) {this.students = }21}    

The last class that writes XML and Java objects to each other ( through the Marshaller class implementation transforms the object into XML, and can also use the Unmarshaller class to convert XML to a class ):

The 1.java object is converted to XML:

1 packageCom.quest.software.bus4j.ui.framework.extend.frameParase.test; 2 3 ImportJava.io.BufferedWriter; 4 ImportJava.io.File; 5 ImportJava.io.FileWriter; 6 ImportJava.io.IOException; 7 ImportJava.io.StringWriter; 8 ImportJava.util.ArrayList; 9 ImportJAVA.UTIL.LIST;10 ImportJAVAX.XML.BIND.JAXBCONTEXT;12 ImportJAVAX.XML.BIND.JAXBEXCEPTION;13 ImportJAVAX.XML.BIND.MARSHALLER;14 public classBeantoxml {/**18 * Java object converted to XML file * @param xmlpath XML file path * @param load Java object. CLASS21 * @return XML file String22 * @throws jaxbexception */24 public static String Beantoxml (Object obj,class<?> Load) throwsjaxbexception{25 Jaxbcontext context =Jaxbcontext.newinstance (load); Marshaller Marshaller =Context.createmarshaller (); Marshaller.setproperty (Marshaller.jaxb_formatted_output, True); Marshaller.setproperty (marshaller.jaxb_encoding, "GBK"); StringWriter writer = newStringWriter (); 30Marshaller.marshal (Obj,writer);Writer.tostring (); 32}33 public static void Main (string[] args) throwsJaxbexception, IOException {list<string> hobby = new arraylist<>( ); Hobby.add ("basketball"),Hobby.add ("Music"), PNS hobby.add ("Table tennis"), list<student> studentlist = New arraylist<>(); Student st = new Student ("Zhang San", "male", 10001, "top class", Hobby); Studentlist.add (ST); Student st1 = new Student ("John Doe", "male", 10002, "normal class", Hobby); Studentlist.add st1 (Student); st2 = new Student ("Lily "," female ", 10003," ordinary Class ", Hobby); Studentlist.add (ST2); studentlist students = new studentlist ();  Students.setstudents (studentlist); String str = beantoxml.beantoxml (students, Studentlist.class); 51 52// Write to XML file Xmlpath = "D:/testconfig.xml"; bufferedwriter bfw = new BufferedWriter (New FileWriter  File (Xmlpath)); bfw.write (str); bfw.close (); }58}       

Test the generated XML file such as:

2.xml Convert to Java object:

1 packageCom.quest.software.bus4j.ui.framework.extend.frameParase.test; 2 3 ImportJava.io.File; 4 ImportJava.io.IOException; 5 ImportJava.util.List; 6 7 ImportJavax.xml.bind.JAXBContext; 8 ImportJavax.xml.bind.JAXBException; 9 ImportJAVAX.XML.BIND.UNMARSHALLER;10 public classXmltobean {/**14 * XML file configuration converted to Object * @param xmlpath XML file path * @param load Java object. CLASS17 * @return Java objects * @throws jaxbexception * @throws IOException20 */21 public static Object Xmltobean (String x Mlpath,class<?> load) throwsJaxbexception, ioexception{22 jaxbcontext context =Jaxbcontext.newinstance (load); Unmarshaller Unmarshaller =Context.createunmarshaller (); Object object = Unmarshaller.unmarshal (newFile (Xmlpath)); return object;26 }27 public static void Main (string[] args) throws IOException, JAX bexception {String Xmlpath = "D:/testconfig.xml"; Object object = Xmltobean.xmltobean (Xmlpath, Studentlist.class) Studentlist students = (studentlist) object;32 list<student> studentlist =  Students.getstudents (); (int i=0;i<studentlist.size (); i++) { System.out.println ( Studentlist.get (i). Name), System.out.println (Studentlist.get (i), sex), PNs System.out.println ( Studentlist.get (i). Number), System.out.println (Studentlist.get (i). ClassName), and the A-Z for(String str: Studentlist.get (i). Hobby) {System.out.print (str+ "); }42 System.out.println ("-------------"); }44 }45}                

The results of the test printing are as follows:

Tom
Man
10001
Top class
Basketball Music Table Tennis-------------
John doe
Man
10002
Regular class
Basketball Music Table Tennis-------------
Lily
Woman
10003
Regular class
Basketball Music Table Tennis-------------

Have not understood can contact me, communicate with each other!
JAXB is very useful, but the XML to Java object when the XML file can not be configured incorrectly, you must strictly follow the Java object of their own definition of the annotations to write XML files, or JAXB inside error is very difficult to find fault!!!

JAXB implements conversion between Java objects and XML

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.