杰瑞科技汇

Java对象如何转为XML?

Of course! Converting a Java object to XML is a common task in enterprise applications, often used for data serialization, configuration, and web services (like SOAP or REST with XML payloads).

Java对象如何转为XML?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering the most popular methods, from the modern standard (JAXB) to more manual approaches.

Summary of Methods

Method When to Use Pros Cons
JAXB (Java Architecture for XML Binding) Recommended for most cases. The standard, built-in way since Java 6. - Standard and built-in into the JDK.
- Simple annotations (@XmlRootElement).
- Handles collections, inheritance, and complex types well.
- Part of Java EE, which is being phased out in favor of Jakarta EE.
- Configuration can get complex for edge cases.
DOM (Document Object Model) When you need to build or manipulate the XML tree structure in memory before serializing. - Full control over the XML structure.
- Standard part of the JDK.
- Verbose and requires manual creation of every element.
- Can be memory-intensive for large documents.
StAX (Streaming API for XML) For high-performance, low-memory footprint scenarios, especially with large XML files. - Event-based, very memory-efficient.
- Faster than DOM for serialization.
- More complex to use than JAXB.
- You are responsible for manually constructing the XML output.
Third-Party Libraries (e.g., XStream, Jackson) When you need more flexibility, a different data model (e.g., JSON), or specific features not in JAXB. - Often very easy to use.
- Rich feature sets (pretty printing, aliases, etc.).
- Jackson is the de-facto standard for JSON and has excellent XML support.
- Adds an external dependency to your project.

Method 1: JAXB (Recommended)

JAXB uses annotations to map Java fields to XML elements. This is the cleanest and most common approach.

Step 1: Create a Java Class with JAXB Annotations

Let's create a Book class. The key annotations are:

  • @XmlRootElement: Maps the class to an XML root element.
  • @XmlElement: Maps a field or property to an XML element.
  • @XmlAttribute: Maps a field or property to an XML attribute.
// Book.java
import javax.xml.bind.annotation.*;
@XmlRootElement(name = "book") // Specifies the root element name
@XmlAccessorType(XmlAccessType.FIELD) // Binds fields directly by default
public class Book {
    @XmlAttribute(name = "id") // Maps this field to an XML attribute
    private long id;
    @XmlElement(name = "title") // Maps this field to an XML element
    private String title;
    @XmlElement(name = "author")
    private String author;
    @XmlElement(name = "price")
    private double price;
    // A no-arg constructor is required by JAXB
    public Book() {
    }
    public Book(long id, String title, String author, double price) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.price = price;
    }
    // Getters and Setters are required for JAXB to access the fields
    public long getId() { return id; }
    public void setId(long id) { this.id = id; }
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
    public String getAuthor() { return author; }
    public void setAuthor(String author) { this.author = author; }
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }
}

Step 2: Create a JAXB Context and Marshal the Object

The "marshalling" process is converting a Java object to XML.

Java对象如何转为XML?-图2
(图片来源网络,侵删)
// JaxbExample.java
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.File;
public class JaxbExample {
    public static void main(String[] args) {
        // 1. Create a sample Java object
        Book book = new Book(101L, "Effective Java", "Joshua Bloch", 45.99);
        // 2. Specify the file where the XML will be saved
        File xmlFile = new File("book.xml");
        try {
            // 3. Create a JAXBContext instance. It's the entry point for JAXB.
            //    Pass the class of the object you want to marshal.
            JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
            // 4. Create a Marshaller
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            // 5. Configure the Marshaller for pretty-printing the XML output
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            // 6. Marshal the object to the file
            jaxbMarshaller.marshal(book, xmlFile);
            jaxbMarshaller.marshal(book, System.out); // Also print to console
            System.out.println("\nFile 'book.xml' created successfully!");
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

Step 3: Run and Check the Output

After running JaxbExample.java, you will get a file named book.xml with the following content:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book id="101">Effective Java</title>
    <author>Joshua Bloch</author>
    <price>45.99</price>
</book>

Method 2: Using the DOM API (Manual Approach)

This method gives you full control but is more verbose. You manually build an XML tree in memory.

Step 1: Create the DOM Document and Elements

// DomExample.java
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
public class DomExample {
    public static void main(String[] args) {
        // 1. Create a sample Java object
        Book book = new Book(101L, "Effective Java", "Joshua Bloch", 45.99);
        try {
            // 2. Create a DocumentBuilderFactory and DocumentBuilder
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            // 3. Create a new Document
            Document doc = docBuilder.newDocument();
            // 4. Create the root element (<book>)
            Element rootElement = doc.createElement("book");
            rootElement.setAttribute("id", String.valueOf(book.getId())); // Add attribute
            doc.appendChild(rootElement);
            // 5. Create child elements and append them to the root
            Element title = doc.createElement("title");
            title.appendChild(doc.createTextNode(book.getTitle()));
            rootElement.appendChild(title);
            Element author = doc.createElement("author");
            author.appendChild(doc.createTextNode(book.getAuthor()));
            rootElement.appendChild(author);
            Element price = doc.createElement("price");
            price.appendChild(doc.createTextNode(String.valueOf(book.getPrice())));
            rootElement.appendChild(price);
            // 6. Write the content into an XML file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // Pretty print
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("book_dom.xml"));
            transformer.transform(source, result);
            System.out.println("File 'book_dom.xml' created successfully!");
        } catch (ParserConfigurationException | TransformerException e) {
            e.printStackTrace();
        }
    }
}

Step 3: Check the Output

The output book_dom.xml will be functionally identical to the JAXB version, but the code to generate it is much longer.


Method 3: Using a Third-Party Library (Jackson)

Jackson is extremely popular, especially for JSON, but it also has robust support for XML. You need to add the Jackson dependency first.

Step 1: Add Jackson Dependency

If you're using Maven, add this to your pom.xml:

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

Step 2: Use the ObjectMapper

Jackson's ObjectMapper is very similar to its JSON counterpart.

// JacksonExample.java
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.File;
import java.io.IOException;
public class JacksonExample {
    public static void main(String[] args) {
        // 1. Create a sample Java object
        Book book = new Book(101L, "Effective Java", "Joshua Bloch", 45.99);
        // 2. Create an XmlMapper
        XmlMapper xmlMapper = new XmlMapper();
        try {
            // 3. Write the object to a file (pretty printing by default)
            xmlMapper.writerWithDefaultPrettyPrinter().writeValue(new File("book_jackson.xml"), book);
            System.out.println("File 'book_jackson.xml' created successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Step 3: Check the Output

The book_jackson.xml file will look very similar to the JAXB output. Jackson is also annotation-driven (using its own @JacksonXmlProperty etc.), but it can often work with simple POJOs out of the box.

Which One Should I Choose?

  • For new projects, especially those running on modern Java (9+), JAXB is still an excellent and standard choice. If you're using a framework like Spring Boot, it's straightforward to integrate.
  • If you need ultimate control over the XML structure or are building a document from scratch, the DOM API is the way to go, but be prepared for more code.
  • If you are already using Jackson for JSON in your project, or if you need features it provides (like better integration with other data formats), then using Jackson for XML is a great, consistent choice.
  • Avoid StAX for simple object-to-XML conversion. It's best suited for reading or writing very large XML files where memory is a concern.
分享:
扫描分享到社交APP
上一篇
下一篇