search
HomeBackend DevelopmentXML/RSS TutorialJava&Xml Tutorial (11) JAXB implements XML and Java object conversion


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

}

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>

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, 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>

Run the testXml2Obj test method , console output:

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

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

}

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>

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, 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>

Run the testXml2Obj test method , console output:

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

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
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
JSON, XML, and Data Formats: Comparing RSSJSON, XML, and Data Formats: Comparing RSSMay 02, 2025 am 12:20 AM

The main differences between JSON, XML and RSS are structure and uses: 1. JSON is suitable for simple data exchange, with a simple structure and easy to parse; 2. XML is suitable for complex data structures, with a rigorous structure but complex parsing; 3. RSS is based on XML and is used for content release, standardized but limited use.

Troubleshooting XML/RSS Feeds: Common Pitfalls and Expert SolutionsTroubleshooting XML/RSS Feeds: Common Pitfalls and Expert SolutionsMay 01, 2025 am 12:07 AM

The processing of XML/RSS feeds involves parsing and optimization, and common problems include format errors, encoding issues, and missing elements. Solutions include: 1. Use XML verification tools to check for format errors; 2. Ensure encoding consistency and use the chardet library to detect encoding; 3. Use default values ​​or skip the element when missing elements; 4. Use efficient parsers such as lxml and cache parsing results to optimize performance; 5. Pay attention to data consistency and security to prevent XML injection attacks.

Decoding RSS Documents: Reading and Interpreting FeedsDecoding RSS Documents: Reading and Interpreting FeedsApr 30, 2025 am 12:02 AM

The steps to parse RSS documents include: 1. Read the XML file, 2. Use DOM or SAX to parse XML, 3. Extract headings, links and other information, and 4. Process data. RSS documents are XML-based formats used to publish updated content, structures containing, and elements, suitable for building RSS readers or data processing tools.

RSS and XML: The Cornerstone of Web SyndicationRSS and XML: The Cornerstone of Web SyndicationApr 29, 2025 am 12:22 AM

RSS and XML are the core technologies in network content distribution and data exchange. RSS is used to publish frequently updated content, and XML is used to store and transfer data. Development efficiency and performance can be improved through usage examples and best practices in real projects.

RSS Feeds: Exploring XML's Role and PurposeRSS Feeds: Exploring XML's Role and PurposeApr 28, 2025 am 12:06 AM

XML's role in RSSFeed is to structure data, standardize and provide scalability. 1.XML makes RSSFeed data structured, making it easy to parse and process. 2.XML provides a standardized way to define the format of RSSFeed. 3.XML scalability allows RSSFeed to add new tags and attributes as needed.

Scaling XML/RSS Processing: Performance Optimization TechniquesScaling XML/RSS Processing: Performance Optimization TechniquesApr 27, 2025 am 12:28 AM

When processing XML and RSS data, you can optimize performance through the following steps: 1) Use efficient parsers such as lxml to improve parsing speed; 2) Use SAX parsers to reduce memory usage; 3) Use XPath expressions to improve data extraction efficiency; 4) implement multi-process parallel processing to improve processing speed.

RSS Document Formats: Exploring RSS 2.0 and BeyondRSS Document Formats: Exploring RSS 2.0 and BeyondApr 26, 2025 am 12:22 AM

RSS2.0 is an open standard that allows content publishers to distribute content in a structured way. It contains rich metadata such as titles, links, descriptions, release dates, etc., allowing subscribers to quickly browse and access content. The advantages of RSS2.0 are its simplicity and scalability. For example, it allows custom elements, which means developers can add additional information based on their needs, such as authors, categories, etc.

Understanding RSS: An XML PerspectiveUnderstanding RSS: An XML PerspectiveApr 25, 2025 am 12:14 AM

RSS is an XML-based format used to publish frequently updated content. 1. RSSfeed organizes information through XML structure, including title, link, description, etc. 2. Creating RSSfeed requires writing in XML structure, adding metadata such as language and release date. 3. Advanced usage can include multimedia files and classified information. 4. Use XML verification tools during debugging to ensure that the required elements exist and are encoded correctly. 5. Optimizing RSSfeed can be achieved by paging, caching and keeping the structure simple. By understanding and applying this knowledge, content can be effectively managed and distributed.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.