Java & Xml tutorial (11) JAXB for XML and Java object conversion

Source: Internet
Author: User
Tags xml attribute
JAXB is the abbreviation of javaubuntureforxmlbinding. it is used to establish a ing between Java classes and XML, which helps developers easily convert XML and Java objects to each other.


JAXB is short for Java Architecture for XML Binding. it is used to establish a ing between Java classes and XML, which helps developers easily convert XML and Java objects.
This article introduces the use of JAXB with a simple example. First, we need to understand the common APIs of JAXB.

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

  • The Marshaller interface serializes Java objects into XML data.

  • Unserializedaller interface to deserialize XML data 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 automatically bind each non-static (static) and non-transient (marked by @ XmlTransient) FIELD in the Java class 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.

The content of the Java Bean to be bound is as follows:
Employee. java

package net.csdn.beans;import javax.xml.bind.annotation.XmlAccessType;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlType;@XmlAccessorType(XmlAccessType.FIELD)  @XmlRootElement  @XmlType(name = "Employee", propOrder = { "name", "age", "role", "gender" }) public class Employee {    private String name;        private String gender;        private int age;        private String role;        public String getName() {            return name;    }    public void setName(String name) {            this.name = name;    }    public String getGender() {            return gender;    }    public void setGender(String gender) {            this.gender = gender;    }    public int getAge() {            return age;    }    public void setAge(int age) {            this.age = age;    }    public String getRole() {            return role;    }    public void setRole(String role) {            this.role = role;    }    @Override    public String toString() {            return "Employee:: Name=" + this.name + " Age=" + this.age + " Gender="                + this.gender + " Role=" + this.role;    }}

The content of the XML file to be converted to a Java object is as follows:
Employee. xml

 
     
  
   Pankaj
      29    
  
   Java Developer
      
  
   Male
  
 

Next, write the test case code:
TestJAXB. java

package net.csdn.test;import java.io.InputStream;import java.io.StringReader;import java.io.StringWriter;import javax.xml.bind.JAXBContext;import javax.xml.bind.Marshaller;import javax.xml.bind.Unmarshaller;import net.csdn.beans.Employee;import org.junit.Test;public class TestJAXB {    @Test    public void testXml2Obj() throws Exception {        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("employee.xml");        byte[] bytes = new byte[is.available()];        is.read(bytes);        String xmlStr = new String(bytes);        JAXBContext context = JAXBContext.newInstance(Employee.class);          Unmarshaller unmarshaller = context.createUnmarshaller();          Employee emp = (Employee) unmarshaller.unmarshal(new StringReader(xmlStr));        System.out.println(emp);    }    @Test    public void testObj2Xml() {        Employee  emp = new Employee();        emp.setAge(10);        emp.setGender("Male");        emp.setName("Jane");        emp.setRole("Teacher");        String xmlStr = TestJAXB.convertToXml(emp,"utf-8");          System.out.println(xmlStr);    }    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 e) {              e.printStackTrace();          }          return result;      } }

Run the testObj2Xml test method. the console outputs:

 
     
  
   Jane
      10    
  
   Teacher
      
  
   Male
  
 

Run the testXml2Obj test method. the console outputs:

Employee:: Name=Pankaj Age=29 Gender=Male Role=Java Developer

Note: In this example, JUnit4 is used as a unit test tool. in Eclipse, click Window> Show View> OutLine to open the outline View, right-click the testXml2Obj and testObj2Xml methods and choose Run As> JUnit Test.

JAXB is short for Java Architecture for XML Binding. it is used to establish a ing between Java classes and XML, which helps developers easily convert XML and Java objects.
This article introduces the use of JAXB with a simple example. First, we need to understand the common APIs of JAXB.

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

  • The Marshaller interface serializes Java objects into XML data.

  • Unserializedaller interface to deserialize XML data 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 automatically bind each non-static (static) and non-transient (marked by @ XmlTransient) FIELD in the Java class 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.

The content of the Java Bean to be bound is as follows:
Employee. java

package net.csdn.beans;import javax.xml.bind.annotation.XmlAccessType;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlType;@XmlAccessorType(XmlAccessType.FIELD)  @XmlRootElement  @XmlType(name = "Employee", propOrder = { "name", "age", "role", "gender" }) public class Employee {    private String name;        private String gender;        private int age;        private String role;        public String getName() {            return name;    }    public void setName(String name) {            this.name = name;    }    public String getGender() {            return gender;    }    public void setGender(String gender) {            this.gender = gender;    }    public int getAge() {            return age;    }    public void setAge(int age) {            this.age = age;    }    public String getRole() {            return role;    }    public void setRole(String role) {            this.role = role;    }    @Override    public String toString() {            return "Employee:: Name=" + this.name + " Age=" + this.age + " Gender="                + this.gender + " Role=" + this.role;    }}

The content of the XML file to be converted to a Java object is as follows:
Employee. xml

 
     
  
   Pankaj
      29    
  
   Java Developer
      
  
   Male
  
 

Next, write the test case code:
TestJAXB. java

package net.csdn.test;import java.io.InputStream;import java.io.StringReader;import java.io.StringWriter;import javax.xml.bind.JAXBContext;import javax.xml.bind.Marshaller;import javax.xml.bind.Unmarshaller;import net.csdn.beans.Employee;import org.junit.Test;public class TestJAXB {    @Test    public void testXml2Obj() throws Exception {        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("employee.xml");        byte[] bytes = new byte[is.available()];        is.read(bytes);        String xmlStr = new String(bytes);        JAXBContext context = JAXBContext.newInstance(Employee.class);          Unmarshaller unmarshaller = context.createUnmarshaller();          Employee emp = (Employee) unmarshaller.unmarshal(new StringReader(xmlStr));        System.out.println(emp);    }    @Test    public void testObj2Xml() {        Employee  emp = new Employee();        emp.setAge(10);        emp.setGender("Male");        emp.setName("Jane");        emp.setRole("Teacher");        String xmlStr = TestJAXB.convertToXml(emp,"utf-8");          System.out.println(xmlStr);    }    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 e) {              e.printStackTrace();          }          return result;      } }

Run the testObj2Xml test method. the console outputs:

 
     
  
   Jane
      10    
  
   Teacher
      
  
   Male
  
 

Run the testXml2Obj test method. the console outputs:

Employee:: Name=Pankaj Age=29 Gender=Male Role=Java Developer

Note: In this example, JUnit4 is used as a unit test tool. in Eclipse, click Window> Show View> OutLine to open the outline View, right-click the testXml2Obj and testObj2Xml methods and choose Run As> JUnit Test.

The above is the Java & Xml tutorial (11) JAXB implementation of XML and Java object conversion content. For more information, please follow the PHP Chinese network (www.php1.cn )!

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.