java& XML Tutorial (11) JAXB implements XML and Java object transformations

Source: Internet
Author: User

JAXB is the abbreviation for the Java Architecture for XML binding, which is used to establish a mapping between Java classes and XML to help developers easily convert XML and Java objects to each other.
This article introduces the use of JAXB in a simple example. First we need to look at the APIs that JAXB uses frequently.

    • Jaxbcontext class. Is the entrance to the application. Used to manage Xml/java binding information.
    • Marshaller interface. Serializes a Java object into XML data.
    • Unmarshaller interface that deserializes XML data into Java objects.

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

    • @XmlAccessorType (Xmlaccesstype.field). Controls the serialization of a field or property. field indicates that JAXB will voluntarily bind itself to each non-static (static), non-transient (@xmltransient callout) field in the Java class to XML.

      Other values are Xmlaccesstype.property and Xmlaccesstype.none.

    • @XmlAccessorOrder, controlling the ordering of properties 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 to XML.

    • @XmlElementWrapper, for arrays or collections (that is, member variables that include multiple elements), generate an XML element (called a wrapper) that wraps the array or collection.
    • @XmlRootElement, Map a Java class or enumeration type to an XML element.
    • @XmlElement, a property of the Java class is mapped to an XML element with the same name as the property.

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

We need to bind Java bean content such as the following:
Employee.java

 PackageNet.csdn.beans;ImportJavax.xml.bind.annotation.XmlAccessType;ImportJavax.xml.bind.annotation.XmlAccessorType;ImportJavax.xml.bind.annotation.XmlRootElement;ImportJavax.xml.bind.annotation.XmlType;@XmlAccessorType(Xmlaccesstype.field)@XmlRootElement  @XmlType(name ="Employee", Proporder = {"Name","Age","Role","Gender"}) Public  class Employee {    PrivateString name;PrivateString gender;Private intAgePrivateString role; PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } PublicStringGetgender() {returnGender } Public void Setgender(String gender) { This. gender = gender; } Public int Getage() {returnAge } Public void Setage(intAge) { This. Age = Age; } PublicStringGetrole() {returnRole } Public void Setrole(String role) { This. role = role; }@Override     PublicStringtoString() {return "Employee:: Name="+ This. Name +"Age="+ This. Age +"Gender="+ This. Gender +"role="+ This. role; }}

XML file contents that need to be converted to Java objects such as the following:
Employee.xml

<?

xml version="1.0"?><employee id="1"> <name>Pankaj</name> <age>29</age> <role>Java Developer</role> <gender>Male</gender></employee>

Next, write the sample code:
Testjaxb.java

Package Net. Csdn. Test;Import Java. IO. InputStream;Import Java(i). 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(Ten);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; } }

Perform the Testobj2xml test method. Console output:

<?xml version="1.0" encoding="utf-8" standalone="yes"?><employee>    <name>Jane</name>    <age>10</age>    <role>Teacher</role>    <gender>Male</gender></employee>

Perform the Testxml2obj test method. Console output:

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

Note: In this example, using JUNIT4 as the Unit Test tool, click the Window->show view->outline menu in Eclipse to open the outline view, Right-click on the Testxml2obj and Testobj2xml methods to->run as->junit test.

java&amp; XML Tutorial (11) JAXB implements XML and Java object transformations

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.