杰瑞科技汇

Java Bean如何高效转换为XML?

Of course! Converting a Java Bean (a simple POJO) to an XML representation is a common task in Java. There are several excellent libraries to achieve this, each with its own strengths.

Java Bean如何高效转换为XML?-图1
(图片来源网络,侵删)

I'll cover the three most popular and robust methods:

  1. JAXB (Java Architecture for XML Binding): The standard, built-in Java EE solution. It's annotation-based and very powerful.
  2. Jackson with XML Module: A popular choice if you're already using Jackson for JSON. It's fast and flexible.
  3. XStream: A very simple and lightweight library, great for quick tasks.

Let's use a consistent Java Bean for all examples.

The Java Bean (Book.java)

This is a simple Plain Old Java Object (POJO) that we want to convert to XML.

import javax.xml.bind.annotation.*;
import java.util.Date;
// This annotation tells JAXB that this class is the root element of the XML.
@XmlRootElement(name = "book")
// This annotation tells JAXB to use this class's name as the XML element name.
// Without it, JAXB would use the class name "Book".
@XmlAccessorType(XmlAccessType.FIELD) // Specifies that fields are used for binding
public class Book {
    // This annotation maps the field to an XML element.
    @XmlElement(name = "title")
    private String title;
    // If you want to change the attribute name in XML, use @XmlAttribute
    @XmlAttribute(name = "isbn")
    private String isbn;
    @XmlElement(name = "author")
    private String author;
    @XmlElement(name = "published-date")
    private Date publishedDate;
    // A default no-arg constructor is REQUIRED by JAXB
    public Book() {
    }
    public Book(String title, String isbn, String author, Date publishedDate) {
        this.title = title;
        this.isbn = isbn;
        this.author = author;
        this.publishedDate = publishedDate;
    }
    // Getters and Setters are REQUIRED by JAXB
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
    public String getIsbn() { return isbn; }
    public void setIsbn(String isbn) { this.isbn = isbn; }
    public String getAuthor() { return author; }
    public void setAuthor(String author) { this.author = author; }
    public Date getPublishedDate() { return publishedDate; }
    public void setPublishedDate(Date publishedDate) { this.publishedDate = publishedDate; }
}

Method 1: Using JAXB (Recommended for most cases)

JAXB is part of the Java Standard Edition since Java 6, so no external libraries are needed for standard projects.

Java Bean如何高效转换为XML?-图2
(图片来源网络,侵删)

How it Works:

You use annotations on your POJO to define how it should map to XML. Then, you use a JAXBContext to create a Marshaller, which performs the conversion.

Code Example:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;
import java.util.Date;
public class JaxbExample {
    public static void main(String[] args) {
        // 1. Create an instance of your Java Bean
        Book book = new Book("Effective Java", "978-0134685991", "Joshua Bloch", new Date());
        try {
            // 2. Create a JAXBContext instance, passing the class of the object to be marshalled
            JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
            // 3. Create a Marshaller
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            // 4. Configure the Marshaller for pretty-printing (optional)
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            // 5. Create a StringWriter to hold the XML output
            StringWriter sw = new StringWriter();
            // 6. Marshal the Java object to the StringWriter
            jaxbMarshaller.marshal(book, sw);
            // 7. Get the XML as a String
            String xml = sw.toString();
            // Print the result
            System.out.println(xml);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

Expected XML Output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book isbn="978-0134685991">Effective Java</title>
    <author>Joshua Bloch</author>
    <published-date>2025-10-27T10:30:00.123Z</published_date>
</book>

Method 2: Using Jackson with XML Module

Jackson is a high-performance JSON processor, but it also has excellent support for XML via its jackson-dataformat-xml module. This is a great choice if you're already in the Jackson ecosystem.

Step 1: Add Dependency

You need to add the Jackson XML module to your project. For Maven:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.15.2</version> <!-- Use the latest version -->
</dependency>

How it Works:

Jackson uses its own set of annotations (@JacksonXmlProperty, etc.) which are very similar to JAXB's. You create an ObjectMapper configured for XML and call its writeValueAsString() method.

Code Example:

First, you need to slightly modify the Book.java class to use Jackson's annotations.

// Book.java (modified for Jackson)
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import java.util.Date;
@JacksonXmlRootElement(localName = "book") // localName is the XML element name
public class Book {
    @JacksonXmlProperty(isAttribute = true, localName = "isbn")
    private String isbn;
    @JacksonXmlProperty(localName = "title")
    private String title;
    @JacksonXmlProperty(localName = "author")
    private String author;
    @JacksonXmlProperty(localName = "published-date")
    private Date publishedDate;
    public Book() {}
    public Book(String title, String isbn, String author, Date publishedDate) {
        this.title = title;
        this.isbn = isbn;
        this.author = author;
        this.publishedDate = publishedDate;
    }
    // Getters and Setters...
    // (Same getters and setters as before)
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
    public String getIsbn() { return isbn; }
    public void setIsbn(String isbn) { this.isbn = isbn; }
    public String getAuthor() { return author; }
    public void setAuthor(String author) { this.author = author; }
    public Date getPublishedDate() { return publishedDate; }
    public void setPublishedDate(Date publishedDate) { this.publishedDate = publishedDate; }
}

Now, the main class:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.util.Date;
public class JacksonExample {
    public static void main(String[] args) {
        Book book = new Book("Clean Code", "978-0132350884", "Robert C. Martin", new Date());
        try {
            // Create an XmlMapper, which is an ObjectMapper for XML
            XmlMapper xmlMapper = new XmlMapper();
            // Convert the Book object to a pretty-printed XML string
            String xml = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(book);
            System.out.println(xml);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Expected XML Output:

<?xml version="1.0" encoding="UTF-8"?>
<book xmlns:ns2="http://JacksonExample">
  <isbn>978-0132350884</isbn>Clean Code</title>
  <author>Robert C. Martin</author>
  <published-date>2025-10-27T10:30:00.123Z</published-date>
</book>

(Note: The namespace xmlns:ns2 is sometimes added by Jackson. You can configure the mapper to avoid it if needed.)


Method 3: Using XStream

XStream is known for its simplicity and requires no annotations on your POJO, making it very clean for your Java objects.

Step 1: Add Dependency

For Maven:

<dependency>
    <groupId>com.thoughtworks.xstream</groupId>
    <artifactId>xstream</artifactId>
    <version>1.4.20</version> <!-- Use the latest version -->
</dependency>

How it Works:

XStream uses reflection by default to convert objects. You can create aliases for class and field names to control the XML output. It's extremely simple to get started with.

Code Example:

No changes are needed to the original Book.java class.

import com.thoughtworks.xstream.XStream;
import java.util.Date;
public class XStreamExample {
    public static void main(String[] args) {
        Book book = new Book("Design Patterns", "978-0202533610", "Erich Gamma", new Date());
        // 1. Create an XStream instance
        XStream xstream = new XStream();
        // 2. Create aliases for cleaner XML names (optional but recommended)
        xstream.alias("book", Book.class);
        xstream.aliasField("title", Book.class, "title");
        xstream.aliasField("author", Book.class, "author");
        xstream.aliasField("published-date", Book.class, "publishedDate");
        xstream.aliasAttribute(Book.class, "isbn", "isbn");
        // 3. Convert the object to XML
        String xml = xstream.toXML(book);
        System.out.println(xml);
    }
}

Expected XML Output:

<book isbn="978-0202533610">Design Patterns</title>
  <author>Erich Gamma</author>
  <published-date>2025-10-27T10:30:00.123Z</published-date>
</book>

Summary: Which One Should You Choose?

Feature JAXB Jackson (XML Module) XStream
Ease of Use Very good with annotations. Good, similar to JAXB. Excellent, no annotations needed.
Performance Good. Excellent (very fast). Good.
Flexibility Good, standard for Java EE. Excellent, part of a larger data processing framework. Excellent, very easy to configure aliases.
Dependencies Built-in to Java SE 6+. Requires jackson-dataformat-xml. Requires xstream library.
Best For Standard Java applications, enterprise environments. If you're in a Java EE/Jakarta EE environment, this is the natural choice. REST APIs, microservices. If you already use Jackson for JSON, this is the most consistent choice. Rapid prototyping, simple conversions, or when you cannot add annotations to your POJOs.
分享:
扫描分享到社交APP
上一篇
下一篇