Java Jaxb JavaBean and XML Conversion

Source: Internet
Author: User
Tags xml attribute

Java Jaxb JavaBean and XML Conversion

1. Jaxb-Java Arcitecture for XML Binding

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

Jaxb2.0 is a component of Jdk1.6. The conversion between Xml and JavaBean can be completed without the support of Third-Party Jar packages.

2. Important concepts:

· JAXBContext class is the application entry for managing binding information in XML/Java.

· The Marshaller interface serializes Java objects into XML data.

· Unserialized aller interface to deserialize XML data into Java objects.

· @ XmlType: ing Java class or enumeration type to XML Schema type

· @ XmlAccessorType (XmlAccessType. FIELD) controls the serialization of fields or attributes. FIELD indicates that JAXB will automatically bind each non-static FIELD in the JAVA class, which is not instantaneous (marked by @ XmlTransient)

XML. Other values include XmlAccessType. PROPERTY and XmlAccessType. NONE.

· @ XmlAccessorOrder: controls the sorting of attributes and fields in the Jaxb binding class.

· XmlJavaTypeAdapter: uses a custom adapter (that is, extends the abstract class XmlAdapter and overwrites the marshal () and unmarshal () Methods) to serialize the Java class as Xml

· @ XmlElementWrapper: For arrays and collections (member variables containing multiple elements), generate an XML Element (called the wrapper) That wraps the array and binds it)

· @ XmlRootElement: maps Java classes or enumeration types to XML elements.

· @ XmlElement: maps an attribute in the Java class to an XML element with the same name as the attribute.

· @ XmlAttribute: maps an attribute of the Java class to an XML Attribute with the same name as the attribute.

3. Application:

The use of Jaxb is very simple. The following is a code written by myself. The Util class is used to convert between a JavaBean and Xml.

JaxbUtil class:Responsible for intercommunication with Jaxb:

Public class JaxbUtil {

Public static String convertToXml (Object obj ){

Return convertToXml (obj, UTF-8 );

}

/**
* @ Note JavaBean convert to xml
* @ Param obj
* JavaBean
* @ Param encoding
* Encoding
* @ Return xml
*/

Public static String convertToXml (Object obj, String encoding ){

String result = null;

Try {

JAXBContext context = JAXBContext. newInstance (obj. getClass ());

Extends aller extends aller = context. createMarshaller ();

Marshaller. setProperty (Marshaller. JAXB_FORMATTED_OUTPUT, true );

Extends aller. setProperty (extends aller. JAXB_ENCODING, encoding );


StringWriter writer = new StringWriter ();

Marshaller. marshal (obj, writer );

Result = writer. toString ();

} Catch (Exception ex ){

}

Return result;

}

/**
* @ Note xml to
* @ Param xml
* Xml
* @ Param c
* JavBean
* @ Return
*/

Public static T convertToJavaBean (String xml, Class 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:Simple 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:The main method is used to test the Bean object.

@ 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 ProvinceList;

 

Public String getName (){

Return name;

}

Public void setName (String name ){

This. name = name;

}

Public List GetProvinceList (){

Return provinceList;

}

Public void setProvinceList (List ProvinceList ){

This. provinceList = provinceList;

}

 

Public static void main (String [] args ){

Collect con = new Collect ();

Con. setName (China );

List List = new ArrayList ();

Province pro = new Province ();

Pro. setName (Jiangsu );

Pro. setProvCity (Nanjing );

Province pro2 = new Province ();

Pro2.setName (Zhejiang );

Pro2.setProvCity (Hangzhou );

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 mentioned above, the conversion between JavaBean and XML is completed. Jaxb is relatively simple to use, and Jaxb does not need to introduce third-party jar for dependency. jdk is responsible for the implementation.

 

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.