JAXB completes conversion between XML and Java objects

Source: Internet
Author: User

During this time, I was so busy that even all the staff on weekends were busy with the progress of the product. I thought that I had been working for 12 consecutive days and people were a little dizzy! At this moment, there is a little time, so I am going to share with you about JAXB. Will anyone feel a little strange? It's okay. Let's briefly describe it with everyone here:

JAXB (Java Architecture for XML Binding) is an industry standard and a technology that can generate Java classes based on XML Schema. In this process, JAXB also provides a way to reverse generate a Java object tree for the XML instance document, and re-write the content of the Java object tree to the XML instance document. On the other hand, JAXB provides a fast and easy way to bind the XML schema to the Java representation, so that Java developers can easily combine XML data and processing functions in Java applications.

The basic knowledge is as much as this. Let's look at the actual situation and prepare the Code:

/*** @ Description: ** @ Title: Student. java * @ Package com. joyce. bean * @ Copyright: Copyright (c) 2014 ** @ author Comsys-LZP * @ date 02:51:41 * @ version V2.0 */package com. joyce. bean; import javax. xml. bind. annotation. xmlAttribute; import javax. xml. bind. annotation. xmlElement; import javax. xml. bind. annotation. xmlRootElement;/*** @ Description: Student Entity class ** @ ClassName: Student * @ Copyright: Copyright (c) 2014 ** @ author Comsys-LZP * @ date 02:51:41 * @ version V2.0 */@ XmlRootElement (name = "Student ") public class Student {/*** name */private String name;/*** Gender */private String sex;/*** age */private Integer age; /*** @ return the name */public String getName () {return name ;} /*** @ param name * the name to set */@ XmlAttributepublic void setName (String name) {this. name = name;}/*** @ return the sex */public String getSex () {return sex ;} /*** @ param sex * the sex to set */@ XmlElementpublic void setSex (String sex) {this. sex = sex;}/*** @ return the age */public Integer getAge () {return age ;} /*** @ param age * the age to set */@ XmlElementpublic void setAge (Integer age) {this. age = age;}/*** @ param name * @ param sex * @ param age */public Student (String name, String sex, Integer age) {super (); this. name = name; this. sex = sex; this. age = age;}/*****/public Student () {super ();}}

Next:
/*** @ Description: ** @ Title: Teacher. java * @ Package com. joyce. bean * @ Copyright: Copyright (c) 2014 ** @ author Comsys-LZP * @ date 04:29:23 * @ version V2.0 */package com. joyce. bean; import java. util. list; import javax. xml. bind. annotation. xmlElement; import javax. xml. bind. annotation. xmlRootElement;/*** @ Description: Instructor entity class ** @ ClassName: Teacher * @ Copyright: Copyright (c) 2014 ** @ author Comsys-LZP * @ date 04:29:23 * @ version V2.0 */@ XmlRootElement (name = "Teacher ") public class Teacher {/*** name */private String name;/*** Gender */private String sex;/*** age */private Integer age; /*** Student */private List <Student> students;/*** @ return the name */public String getName () {return name ;} /*** @ param name * the name to set */@ XmlElementpublic void setName (String name) {this. name = name;}/*** @ return the sex */public String getSex () {return sex ;} /*** @ param sex * the sex to set */@ XmlElementpublic void setSex (String sex) {this. sex = sex;}/*** @ return the age */public Integer getAge () {return age ;} /*** @ param age * the age to set */@ XmlElementpublic void setAge (Integer age) {this. age = age;}/*** @ return the students */public List <Student> getStudents () {return students ;} /*** @ param students * the students to set */@ XmlElement (name = "Student") public void setStudents (List <Student> students) {this. students = students;}/*****/public Teacher () {super ();} /*** @ param name * @ param sex * @ param age */public Teacher (String name, String sex, Integer age) {super (); this. name = name; this. sex = sex; this. age = age;}/*** @ param name * @ param sex * @ param age * @ param students */public Teacher (String name, String sex, Integer age, list <Student> students) {super (); this. name = name; this. sex = sex; this. age = age; this. students = students ;}}

Haha, are you familiar with these two objects! Yes. Here we encapsulate the object to provide a good foundation for the subsequent conversion of Java objects and XML. OK, the key code is coming:
/*** @ Description: ** @ Title: JAXBUtil. java * @ Package com. joyce. util * @ Copyright: Copyright (c) 2014 ** @ author Comsys-LZP * @ date 02:54:40 * @ version V2.0 */package com. joyce. util; import java. io. byteArrayOutputStream; import java. io. file; import javax. xml. bind. JAXBContext; import javax. xml. bind. marshaller; import javax. xml. bind. unmarshaller;/*** @ Description: utixb object and XML Conversion util *** @ ClassName: JAXBUtil * @ Copyright: Copyright (c) 2014 ** @ author Comsys-LZP * @ date 02:54:40 * @ version V2.0 */public class JAXBUtil {/*** @ Description: convert the object to XML ** @ param obj * @ param beanClass * @ return * @ throws Exception ** @ Title: JAXBUtil. java * @ Copyright: Copyright (c) 2014 ** @ author Comsys-LZP * @ date 04:23:45 * @ version V2.0 */@ SuppressWarnings ("unchecked ") public String objectToXmlStr (Object obj, Class beanClass) throws Exception {JAXBContext context = JAXBContext. newInstance (beanClass); // obtain the marshaller object Marshaller extends aller = context according to the context. createMarshaller (); // sets the encoding Character Set marshaller. setProperty (exploraller. JAXB_ENCODING, "UTF-8"); // formatted XML output with branch and indent marshaller. setProperty (exploraller. JAXB_FORMATTED_OUTPUT, true); // print it to the marshaller console. marshal (obj, System. out); ByteArrayOutputStream baos = new ByteArrayOutputStream (); extends aller. marshal (obj, baos); String xmlObj = new String (baos. toByteArray (); return xmlObj. replace ("standalone = \" yes \ "", "");}/*** @ Description: convert the object to XML and write it to the file ** @ param obj * @ param beanClass * @ param file * @ throws Exception ** @ Title: JAXBUtil. java * @ Copyright: Copyright (c) 2014 ** @ author Comsys-LZP * @ date 04:24:13 * @ version V2.0 */@ SuppressWarnings ("unchecked ") public void objectToXmlStr (Object obj, Class beanClass, File file) throws Exception {JAXBContext context = JAXBContext. newInstance (beanClass); // obtain the marshaller object Marshaller extends aller = context according to the context. createMarshaller (); // sets the encoding Character Set marshaller. setProperty (exploraller. JAXB_ENCODING, "UTF-8"); // formatted XML output with branch and indent marshaller. setProperty (exploraller. JAXB_FORMATTED_OUTPUT, true); // print it to the marshaller console. marshal (obj, System. out); extends aller. marshal (obj, file);}/*** @ Description: XML Conversion to object ** @ param <T> * @ param file * @ param beanClass * @ return * @ throws Exception ** @ Title: JAXBUtil. java * @ Copyright: Copyright (c) 2014 ** @ author Comsys-LZP * @ date 04:24:50 * @ version V2.0 */@ SuppressWarnings ("unchecked ") public <T> T xmlStrToObject (File file, Class <T> beanClass) throws Exception {T bean = beanClass. newInstance (); JAXBContext context = JAXBContext. newInstance (beanClass); Unmarshaller unmarshaller = context. createUnmarshaller (); bean = (T) unmarshaller. unmarshal (file); return bean ;}}

This is actually the basis of Java. When it's okay, you can look at the Java source code, Jdk API, and so on. You will see things you may not have thought about! Immediately test:
/*** @ Description: ** @ Title: JAXBTest. java * @ Package com. joyce. test * @ Copyright: Copyright (c) 2014 ** @ author Comsys-LZP * @ date 03:04:05 * @ version V2.0 */package com. joyce. test; import java. io. file; import java. util. arrayList; import java. util. list; import com. joyce. bean. student; import com. joyce. bean. teacher; import com. joyce. util. JAXBUtil;/*** @ Description: Test class ** @ ClassName: JAXBTest * @ Copyright: Copyright (c) 2014 ** @ author Comsys-LZP * @ date 03:04:05 * @ version V2.0 */public class JAXBTest {public static void main (String [] args) {try {Teacher teacher = new Teacher ("JuanJuan", "female", 22); Student student = new Student ("Joyce. luo "," male ", 21); Student student2 = new Student (" Phang. law "," male ", 18); JAXBUtil util = new JAXBUtil (); List <Student> stuList = new ArrayList <Student> (); stuList. add (student); stuList. add (student2); teacher. setStudents (stuList); String xmlTeaStr = util. objectToXmlStr (teacher, Teacher. class); System. out. println ("\ n contains the set of objects into XML: \ n" + xmlTeaStr); String xmlStr = util. objectToXmlStr (student, Student. class); System. out. println ("\ n object converted to XML: \ n" + xmlStr); File file = new File ("str. xml "); System. out. println ("Whether the file exists:" + file. exists (); // util. objectToXmlStr (student, Student. class, file); Student stu = util. xmlStrToObject (file, Student. class); System. out. println ("\ nXML to object: \ n" + stu. getName () + "\ t" + stu. getSex () + "\ t" + stu. getAge ();} catch (Exception e) {e. printStackTrace ();}}}

Result Display:
<? Xml version = "1.0" encoding = "UTF-8" standalone = "yes"?> <Teacher> <age> 22 </age> <name> JuanJuan </name> <sex> female </sex> <Student name = "Joyce. luo "> <age> 21 </age> <sex> male </sex> </Student> <Student name =" Phang. law "> <age> 18 </age> <sex> male </sex> </Student> </Teacher>: <? Xml version = "1.0" encoding = "UTF-8"?> <Teacher> <age> 22 </age> <name> JuanJuan </name> <sex> female </sex> <Student name = "Joyce. luo "> <age> 21 </age> <sex> male </sex> </Student> <Student name =" Phang. law "> <age> 18 </age> <sex> male </sex> </Student> </Teacher> <? Xml version = "1.0" encoding = "UTF-8" standalone = "yes"?> <Student name = "Joyce. Luo"> <age> 21 </age> <sex> male </sex> </Student> Object conversion to XML: <? Xml version = "1.0" encoding = "UTF-8"?> <Student name = "Joyce. luo "> <age> 21 </age> <sex> male </sex> </Student> whether the file exists: trueXML is converted to Joyce. luo male 21

Do you have any suggestions! Full resources: http://download.csdn.net/download/luo201227/7505479

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.