Java JAXB JavaBean and XML interoperability

Source: Internet
Author: User
Tags xml attribute

1.jaxb-java arcitecture for XML Binding

is a standard in the industry and is a technology that can generate Java classes based on XML schemas.

Jaxb2.0 is an integral part of Jdk1.6. The conversion of XML to JavaBean is done without the support of a third-party jar package.

2. Key Concepts:

· The Jaxbcontext class, which is the application's portal, is used to manage Xml/java binding information.

· The Marshaller interface, which serializes Java objects into XML data.

· Unmarshaller interface that deserializes XML data into Java objects.

• @XmlType to map a Java class or enumeration type to an XML Schema type

• @XmlAccessorType (Xmlaccesstype.field) to control the serialization of fields or properties. field indicates that JAXB will automatically bind each non-static, non-instantaneous (denoted by @xmltransient) field in the Java class to the

Xml. Other values are Xmlaccesstype.property and Xmlaccesstype.none.

• @XmlAccessorOrder to control the ordering of properties and fields in the JAXB binding class.

· Xmljavatypeadapter, using custom adapters (that is, extending the abstract class XMLAdapter and overriding the Marshal () and Unmarshal () methods) to serialize the Java class as XML

• @XmlElementWrapper, for arrays and collections (that is, member variables that contain multiple elements), generates an XML element that wraps the array and binds it (called the wrapper)

• @XmlRootElement to map a Java class or enumeration type to an XML element.

• @XmlElement to map an attribute in a Java class to an XML element with the same name as the property.

• @XmlAttribute, Map a property of a Java class to an XML attribute with the same name as the property.

3. Application:

The use of JAXB is very simple, as follows is a code I write, through the Util class to complete the conversion between JavaBean and XML

Jaxbutil class: responsible for the transit with JAXB:

public class Jaxbutil {

public static String converttoxml (Object obj) {

return Converttoxml (obj, "UTF-8");

}

/**
* @note JavaBean to XML
* @param obj
* JavaBean
* @param encoding
* Code
* @return XML
*/

public static string Converttoxml (Object obj, string encoding) {

String result = null;

try {

Jaxbcontext context = Jaxbcontext.newinstance (Obj.getclass ());

Marshaller Marshaller = Context.createmarshaller ();

Marshaller.setproperty (Marshaller.jaxb_formatted_output, true);

Marshaller.setproperty (marshaller.jaxb_encoding, ENCODING);


StringWriter writer = new StringWriter ();

Marshaller.marshal (obj, writer);

result = Writer.tostring ();

} catch (Exception ex) {

}

return result;

}

/**
* @note XML to JavaBean
* @param xml
*Xml
* @param c
*Javbean
* @return
*/

public static <T> T Converttojavabean (String XML, class<t> c) {

T t = null;

try {

Jaxbcontext context = Jaxbcontext.newinstance (c);

Unmarshaller Unmarshaller = Context.createunmarshaller ();

t = (t) Unmarshaller.unmarshal (new StringReader (XML));

} catch (Exception ex) {

Ex.printstacktrace ();

}

return t;

}

}

Simple class: An easy bean object, where the main method is to test it

@XmlAccessorType (Xmlaccesstype.field)

@XmlRootElement

@XmlType (name = "Boook", Proporder = {"Author", "Calendar", "Price", "id"})

public class Simple {

@XmlElement (required = true)

Private String author;

@XmlElement (name= "price_l", Required=true)

private float price;


@XmlElement

Private Date Calendar;


@XmlElement

Private Integer ID;


Public String Getauthor () {

return author;

}

public void Setauthor (String author) {

This.author = author;

}

public float GetPrice () {

return price;

}

public void Setprice (float price) {

This.price = Price;

}

Public Date Getcalendar () {

return calendar;

}

public void Setcalendar (Date calendar) {

This.calendar = Calendar;

}

Public Integer getId () {

return ID;

}

public void SetId (Integer id) {

This.id = ID;

}

public static void Main (string[] agrs) {

Simple simple = new simple ();

Simple.setid (100);

Simple.setauthor ("WANGBC");

Simple.setcalendar (New Date ());

Simple.setprice (23.45f);

String str = jaxbutil.converttoxml (simple);

System.out.println (str);

}

}


Collect class: a more complex bean object, where the main method is the test of it

@XmlAccessorType (Xmlaccesstype.field)

@XmlRootElement (name = "Hard")

@XmlType (Proporder = {"Name", "Provincelist"})

public class Collect {

@XmlElement (name = "Country_name")

private String name;

@XmlElementWrapper (name = "Provinces")

@XmlElement (name = "province")

Private list<province> provincelist;


Public String GetName () {

return name;

}

public void SetName (String name) {

THIS.name = name;

}

Public list<province> getprovincelist () {

return provincelist;

}

public void Setprovincelist (list<province> provincelist) {

This.provincelist = provincelist;

}


public static void Main (string[] args) {

Collect con = new Collect ();

Con.setname ("China");

list<province> list = new arraylist<province> ();

Province Pro = new province ();

Pro.setname ("Jiangsu province");

Pro.setprovcity ("Nanjing");

Province Pro2 = new province ();

Pro2.setname ("Zhejiang province");

Pro2.setprovcity ("Hangzhou city");

List.add (PRO);

List.add (PRO2);

Con.setprovincelist (list);

String str = Jaxbutil.converttoxml (con);

System.out.println (str);

}

}


@XmlAccessorType (Xmlaccesstype.field)

@XmlType (Proporder = {"Name", "Provcity"})

Class Province {

@XmlElement (name = "Province_name")

private String name;

@XmlElement (name = "Prov_city")

Private String provcity;


Public String GetName () {
return name;

}

public void SetName (String name) {

THIS.name = name;

}

Public String getprovcity () {

return provcity;

}

public void setprovcity (String provcity) {

this.provcity = provcity;

}

}
As with the conversion between JavaBean and XML, JAXB is relatively simple to use, and JAXB does not need to introduce a third-party jar to rely on, and the implementation is entirely up to the JDK.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java JAXB JavaBean and XML interoperability

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.