Home Backend Development XML/RSS Tutorial Java&Xml Tutorial (11) JAXB implements XML and Java object conversion

Java&Xml Tutorial (11) JAXB implements XML and Java object conversion

Feb 22, 2017 pm 03:05 PM


JAXB is the abbreviation of Java Architecture for XML Binding, which is used to establish mapping between Java classes and XML, and can help developers easily convert XML and Java objects to each other.
This article uses a simple example to introduce the use of JAXB. First, we need to understand the commonly used APIs of JAXB.

  • The JAXBContext class is the entry point of the application and is used to manage XML/Java binding information.

  • Marshaller interface, serializes Java objects into XML data.

  • Unmarshaller interface, deserializes XML data into Java objects.

  • @XmlType, maps Java classes or enumeration types to XML schema types

  • @XmlAccessorType(XmlAccessType.FIELD), control fields or Serialization of properties. FIELD means that JAXB will automatically bind every non-static (static), non-transient (marked by @XmlTransient) field in the Java class to XML. Other values ​​are XmlAccessType.PROPERTY and XmlAccessType.NONE.

  • @XmlAccessorOrder, controls the ordering of properties and fields in the JAXB binding class

  • @XmlJavaTypeAdapter, uses a customized adapter (that is, extends the abstract class XmlAdapter and override the marshal() and unmarshal() methods) to serialize Java classes to XML.

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

  • @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 we need to bind 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;
    }

}
Copy after login

The content of the XML file that needs to be converted into a Java object is as follows:
employee.xml

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

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;  
    } 

}
Copy after login

Run 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>
Copy after login
Copy after login

Run the testXml2Obj test method , console output:

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

Note: In this example, JUnit4 is used as the unit testing tool. In Eclipse, click the Window->Show View->OutLine menu to open the outline view, respectively on the testXml2Obj and testObj2Xml methods. Right click->Run As->JUnit Test.

JAXB is the abbreviation of Java Architecture for XML Binding, which is used to establish mapping between Java classes and XML, and can help developers easily convert XML and Java objects to each other.
This article uses a simple example to introduce the use of JAXB. First, we need to understand the commonly used APIs of JAXB.

  • The JAXBContext class is the entry point of the application and is used to manage XML/Java binding information.

  • Marshaller interface, serializes Java objects into XML data.

  • Unmarshaller interface, deserializes XML data into Java objects.

  • @XmlType, maps Java classes or enumeration types to XML schema types

  • @XmlAccessorType(XmlAccessType.FIELD), control fields or Serialization of properties. FIELD means that JAXB will automatically bind every non-static (static), non-transient (marked by @XmlTransient) field in the Java class to XML. Other values ​​are XmlAccessType.PROPERTY and XmlAccessType.NONE.

  • @XmlAccessorOrder, controls the ordering of properties and fields in the JAXB binding class

  • @XmlJavaTypeAdapter, uses a customized adapter (that is, extends the abstract class XmlAdapter and override the marshal() and unmarshal() methods) to serialize Java classes to XML.

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

  • @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 we need to bind 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;
    }

}
Copy after login

The content of the XML file that needs to be converted into a Java object is as follows:
employee.xml

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

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;  
    } 

}
Copy after login

Run 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>
Copy after login
Copy after login

Run the testXml2Obj test method , console output:

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

Note: In this example, JUnit4 is used as the unit testing tool. In Eclipse, click the Window->Show View->OutLine menu to open the outline view, respectively on the testXml2Obj and testObj2Xml methods. Right click->Run As->JUnit Test.

The above is the Java&Xml tutorial (11) JAXB implementation of XML and Java object conversion. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles