Sample code for mutual conversion between beans and xml in Jaxb2

Source: Internet
Author: User
Tags xml attribute
The JAXBContext class is an application entry used to manage information bound to XMLJava. Marshaller interface to convert Java pairs into XML data. The Unmarshaller interface converts XML into Java objects. 1. important categories

The JAXBContext class is an application entry used to manage binding information in XML/Java.

Marshaller interface to convert Java pairs into XML data.

The Unmarshaller interface converts XML into Java objects.

@ XmlType: maps Java classes or enumeration types to XML schema types.

@ XmlAccessorType (XmlAccessType. FIELD) controls the serialization of fields or attributes. FIELD indicates that JAXB will be automatically bound to each non-static (static ),

Non-transient (marked by @ XmlTransient) fields to XML. Other values include XmlAccessType. PROPERTY and XmlAccessType. NONE.

@ XmlAccessorOrder: Controls the sorting of attributes and fields in the JAXB binding class.

@ XmlJavaTypeAdapter: use a custom adapter (that is, extend the abstract class XmlAdapter and overwrite the marshal () and unmarshal () methods) to serialize the Java class as XML.

@ XmlElementWrapper: for an array or set (that is, a member variable containing multiple elements), an XML element (called the wrapper) that wraps the array or set is generated ).

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

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

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

II. instances

1. JavaBean

import java.util.Date;import java.util.List;import javax.xml.bind.annotation.XmlAccessType;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlElementWrapper;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlType;import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;import com.tzz.util.xml.JaxbDateSerializer;@XmlAccessorType(XmlAccessType.FIELD)@XmlRootElement(name = "country")@XmlType(propOrder = { "id", "createDate", "name", "provinceList" })public class Country {private Integer id;@XmlJavaTypeAdapter(JaxbDateSerializer.class)private Date createDate;@XmlElement(name = "name")private String name;@XmlElementWrapper(name = "provinces")@XmlElement(name = "province")private List
 
   provinceList;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public Date getCreateDate() {return createDate;}public void setCreateDate(Date createDate) {this.createDate = createDate;}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;}}
   
  
 
import javax.xml.bind.annotation.XmlAccessType;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlType;@XmlAccessorType(XmlAccessType.FIELD)@XmlType(propOrder = { "name", "provCity" })public class Province {@XmlElement(name = "name")private String name;@XmlElement(name = "provCity")private String provCity;public String getProvCity() {return provCity;}public void setProvCity(String provCity) {this.provCity = provCity;}public String getName() {return name;}public void setName(String name) {this.name = name;}}

2. conversion tool

Import java. io. stringReader; import java. io. stringWriter; import javax. xml. bind. JAXBContext; import javax. xml. bind. JAXBException; import javax. xml. bind. marshaller; import javax. xml. bind. unmarshaller;/*** Jaxb 2.0 **/public class JaxbXmlUtil {@ SuppressWarnings ("unchecked") public static
 
  
T xmlToBean (String xml, Class
  
   
BeanClass) {try {JAXBContext jaxbContext = JAXBContext. newInstance (beanClass); Unmarshaller unmarshaller = jaxbContext. createUnmarshaller (); T user = (T) unmarshaller. unmarshal (new StringReader (xml); return user;} catch (JAXBException e) {e. printStackTrace (); return null ;}/ ** convert Bean to XML */public static String beanToXml (Object obj) {String result = null; try {JAXBContext context = JAXBContext. newInstance (obj. getClass (); extends aller = context. createMarshaller (); // determines whether to format the data when it is converted to xml (that is, to automatically wrap the data according to tags; otherwise, it is the xml of a row) into aller. setProperty (exploraller. JAXB_FORMATTED_OUTPUT, true); // extends aller. the JAXB_ENCODING xml encoding method is marshaller. setProperty (exploraller. JAXB_ENCODING, "UTF-8"); StringWriter writer = new StringWriter (); extends aller. marshal (obj, writer); result = writer. toString ();} catch (Exception e) {e. printStackTrace ();} return result ;}}
  
 

3. test class

Import java. text. simpleDateFormat; import java. util. arrayList; import java. util. date; import java. util. list; import org. junit. test; import com. tzz. test. util. xml. entity. country; import com. tzz. test. util. xml. entity. province; import com. tzz. util. xml. jaxbXmlUtil; public class TestJaxbBeanToXmlUtil {@ Testpublic void testBeanToXml () {Country country = new Country (); country. setId (1); country. setCreateDate (new Date (); country. setName ("China"); List
 
  
List = new ArrayList
  
   
(); Province province = new Province (); province. setName ("Guangdong province"); province. setProvCity ("Guangzhou City"); Province province2 = new Province (); province2.setName ("Hunan Province"); province2.setProvCity ("Changsha City"); list. add (province); list. add (province2); country. setProvinceList (list); String xml = JaxbXmlUtil. beanToXml (country); System. out. println (xml) ;}@ Testpublic void testXmlToBean () {String xml ="
   "+"
   
    
"+"
    
     
1
    "+"
    
     
09:36:01
    "+"
    
     
China
    "+"
    
     
"+"
     
      
        Guangdong
      
      
        Guangzhou
      
     "+"
     
      
        Hunan province
      
      
        Changsha city
      
     "+"
    "+"
   "; Country country = JaxbXmlUtil. xmlToBean (xml, Country. class); System. out. println (country. getId () + "--" + new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss "). format (country. getCreateDate () + "--" + country. getName (); for (Province p: country. getProvinceList () {System. out. println (p. getName () + "---" + p. getProvCity ());}}}
  
 

4. test results

4.1 run the testBeanToXml method

 
     
  
   
1
      
  
   
05:24:57
      
  
   
China
      
          
               
    
     
Guangdong
                
    
     
Guangzhou
            
           
               
    
     
Hunan province
                
    
     
Changsha city
            
       
  
 

4.2 run the testXmlToBean method

1--2016-03-10 09:36:01 -- Guangdong province, China --- Guangzhou Hunan province --- Changsha City

The above is a detailed explanation of the sample code for Bean and xml conversion in Jaxb2. For more information, see other related articles in the first PHP community!

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.