杰瑞科技汇

Java文档如何转XML?

Of course! Converting a Java object to an XML document is a common task, often referred to as XML Serialization or Marshalling. There are several excellent libraries in Java to achieve this, each with its own strengths.

Java文档如何转XML?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering the most popular methods:

  1. JAXB (Java Architecture for XML Binding) - The Standard & Recommended Way
  2. Jackson with XML Module - The Flexible & Modern Choice
  3. XStream - The Simple & Powerful Choice

Method 1: JAXB (Java Architecture for XML Binding)

JAXB was part of the standard Java library (JDK) up to Java 8. Since Java 9, it has been in the java.xml.bind module, which is no longer included by default. You need to add it as a dependency if you're using Java 9+.

Why use JAXB?

  • Standard: It's the official Java standard for XML binding.
  • Annotation-Based: Uses simple annotations to control the XML output.
  • Built-in Support: Has excellent integration with JAX-WS and other Java EE technologies.

Step-by-Step Example with JAXB

Add Dependencies (for Java 9+)

If you're using a build tool like Maven, add the following dependency:

Java文档如何转XML?-图2
(图片来源网络,侵删)
<!-- For Java 9+ -->
<dependency>
    <groupId>jakarta.xml.bind</groupId>
    <artifactId>jakarta.xml.bind-api</artifactId>
    <version>4.0.1</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>4.0.4</version>
</dependency>

(Note: For older projects using Java 8 or below, you would use javax.xml.bind instead of jakarta.xml.bind).

Create the Java Class (POJO - Plain Old Java Object)

Create a class that you want to convert to XML. Use JAXB annotations to define how the object maps to XML.

import jakarta.xml.bind.annotation.*;
import java.util.List;
// The root element of the XML will be <book>
@XmlRootElement(name = "book")
// This will cause the class to be written in order of the fields
@XmlAccessorType(XmlAccessType.FIELD)
public class Book {
    // Map this field to an XML attribute <book id="123">
    @XmlAttribute
    private int id;
    // Map this field to an XML element <title>
    private String title;
    // Map this field to an XML element <author>
    private String author;
    // This field will be a nested element <genre>
    private String genre;
    // A list of objects will be automatically wrapped in a collection element
    // e.g., <reviews><review>...</review></reviews>
    private List<String> reviews;
    // No-argument constructor is required by JAXB
    public Book() {
    }
    public Book(int id, String title, String author, String genre) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.genre = genre;
    }
    // Getters and Setters are required for all fields
    public int getId() { return id; }
    public void setId(int 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 String getGenre() { return genre; }
    public void setGenre(String genre) { this.genre = genre; }
    public List<String> getReviews() { return reviews; }
    public void setReviews(List<String> reviews) { this.reviews = reviews; }
    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", author='" + author + '\'' +
                ", genre='" + genre + '\'' +
                '}';
    }
}

Write the Java Code to Convert to XML

Java文档如何转XML?-图3
(图片来源网络,侵删)

You'll need a JAXBContext to manage the binding. The marshaller is the object that performs the conversion.

import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;
import java.io.StringWriter;
import java.util.Arrays;
public class JaxbExample {
    public static void main(String[] args) {
        // 1. Create an instance of the object to be marshalled
        Book book = new Book();
        book.setId(101);
        book.setTitle("The Lord of the Rings");
        book.setAuthor("J.R.R. Tolkien");
        book.setGenre("Fantasy");
        book.setReviews(Arrays.asList("A masterpiece!", "Epic adventure."));
        // 2. Create a JAXBContext instance for the Book class
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
            // 3. Create a Marshaller
            Marshaller marshaller = jaxbContext.createMarshaller();
            // 4. Configure the Marshaller for pretty-printing (optional)
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            // 5. Create a StringWriter to write the XML to
            StringWriter writer = new StringWriter();
            // 6. Marshal the book object to the StringWriter
            marshaller.marshal(book, writer);
            // 7. Print the resulting XML
            String xmlString = writer.toString();
            System.out.println(xmlString);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

Output XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book id="101">The Lord of the Rings</title>
    <author>J.R.R. Tolkien</author>
    <genre>Fantasy</genre>
    <reviews>A masterpiece!</reviews>
    <reviews>Epic adventure.</reviews>
</book>

Method 2: Jackson with XML Module

Jackson is a very popular library for handling JSON, but it also has a powerful module for XML.

Why use Jackson?

  • Fast and Powerful: Known for its high performance.
  • Flexible: Can be configured in many ways.
  • Ecosystem: Part of a larger family of libraries (JSON, CSV, etc.).

Step-by-Step Example with Jackson

Add Dependencies

You need both the core Jackson library and the XML module.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.15.2</version>
</dependency>

Create the Java Class (POJO)

Jackson uses the same annotations as JAXB (and JSON), making it easy to switch.

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import java.util.List;
// The root element of the XML will be <book>
@JacksonXmlRootElement(localName = "book")
public class Book {
    // localName specifies the XML element name
    @JacksonXmlProperty(localName = "title")
    private String title;
    // isAttribute makes this an XML attribute
    @JacksonXmlProperty(isAttribute = true, localName = "id")
    private int id;
    @JacksonXmlProperty(localName = "author")
    private String author;
    @JacksonXmlProperty(localName = "genre")
    private String genre;
    @JacksonXmlProperty(localName = "reviews")
    private List<String> reviews;
    // No-arg constructor, getters, and setters...
    // (Same as the JAXB example)
    public Book() {}
    // ... constructor, getters, setters ...
}

Write the Java Code to Convert to XML

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.IOException;
import java.util.Arrays;
public class JacksonExample {
    public static void main(String[] args) {
        // 1. Create an instance of the object
        Book book = new Book();
        book.setId(101);
        book.setTitle("The Lord of the Rings");
        book.setAuthor("J.R.R. Tolkien");
        book.setGenre("Fantasy");
        book.setReviews(Arrays.asList("A masterpiece!", "Epic adventure."));
        // 2. Create an XmlMapper
        XmlMapper xmlMapper = new XmlMapper();
        try {
            // 3. Convert the object to a pretty-printed XML string
            String xmlString = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(book);
            // 4. Print the resulting XML
            System.out.println(xmlString);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

The output will be very similar to the JAXB example.


Method 3: XStream

XStream is known for its simplicity and powerful features, like not requiring

分享:
扫描分享到社交APP
上一篇
下一篇