杰瑞科技汇

Java XML如何高效转String?

Of course! Converting an XML object to a String is a common task in Java. The best method depends on the XML API you are using. Here are the most common ways to do it, from the modern standard (JAXB) to the classic APIs (DOM, SAX, StAX).

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

Summary: Which Method to Use?

Method Best For Key Advantage Key Disadvantage
JAXB Most modern applications. Binding Java objects to XML. Clean, annotation-driven, very high-level. Requires Java 7+ or a JAXB 2.x implementation for older Java.
DOM Reading, modifying, and writing small XML documents. Easy to navigate and manipulate the XML tree. High memory usage for large files.
StAX (XMLStreamWriter) Writing large XML files or performance-critical applications. Memory-efficient (streaming), fast, and easy to use for writing. More verbose than JAXB. Not ideal for reading.
SAX Parsing very large XML files where memory is a concern. Extremely low memory footprint. Read-only, complex to use (event-driven), harder to generate output.

Using JAXB (Java Architecture for XML Binding) - Recommended

JAXB is the standard for binding Java classes to XML representations. It's the cleanest and most object-oriented approach. Since Java 7, JAXB is included in the JDK. For Java 6 or earlier, you need to add the JAXB libraries (e.g., from javax.xml.bind:jaxb-api and org.glassfish.jaxb:jaxb-runtime).

Step 1: Create a Java class with JAXB annotations

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement // Marks this class as the root of an XML element
public class Book {
    private String title;
    private String author;
    private double price;
    // A no-arg constructor is required by JAXB
    public Book() {}
    public Book(String title, String author, double price) {
        this.title = title;
        this.author = author;
        this.price = price;
    }
    @XmlElement // Marks this field as an XML element
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    @XmlElement
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    @XmlElement
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
}

Step 2: Use a JAXB instance to marshal (convert) the object to a String

import javax.xml.bind.JAXB;
import java.io.StringWriter;
public class JaxbExample {
    public static void main(String[] args) {
        // 1. Create a Java object
        Book book = new Book("Effective Java", "Joshua Bloch", 45.99);
        // 2. Create a StringWriter to hold the XML output
        StringWriter writer = new StringWriter();
        // 3. Marshal the object to XML and write it to the StringWriter
        // JAXB.marshal(object, writer);
        JAXB.marshal(book, writer);
        // 4. Get the String from the StringWriter
        String xmlString = writer.toString();
        // 5. Print the result
        System.out.println(xmlString);
    }
}

Output:

Java XML如何高效转String?-图2
(图片来源网络,侵删)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Book>Effective Java</title>
    <author>Joshua Bloch</author>
    <price>45.99</price>
</Book>

Using DOM (Document Object Model)

The DOM API parses the entire XML document into a tree structure in memory. You can then create this tree and convert it to a String. This is more manual than JAXB.

import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;
public class DomExample {
    public static void main(String[] args) throws Exception {
        // 1. Create a DocumentBuilderFactory
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        // 2. Create a new Document
        Document doc = docBuilder.newDocument();
        // 3. Create the root element and append it to the document
        org.w3c.dom.Element rootElement = doc.createElement("Book");
        doc.appendChild(rootElement);
        // 4. Create and append child elements
        org.w3c.dom.Element title = doc.createElement("title");
        title.appendChild(doc.createTextNode("Effective Java"));
        rootElement.appendChild(title);
        org.w3c.dom.Element author = doc.createElement("author");
        author.appendChild(doc.createTextNode("Joshua Bloch"));
        rootElement.appendChild(author);
        org.w3c.dom.Element price = doc.createElement("price");
        price.appendChild(doc.createTextNode("45.99"));
        rootElement.appendChild(price);
        // 5. Use a Transformer to convert the DOM object to a String
        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");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        String xmlString = writer.toString();
        System.out.println(xmlString);
    }
}

Output:

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

Using StAX (Streaming API for XML) - XMLStreamWriter

StAX is a streaming API, which is very efficient for writing large XML files because it doesn't load the whole document into memory. You create the XML string sequentially.

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.StringWriter;
public class StaxExample {
    public static void main(String[] args) throws XMLStreamException {
        StringWriter stringWriter = new StringWriter();
        XMLOutputFactory factory = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = factory.createXMLStreamWriter(stringWriter);
        try {
            // Start the document
            writer.writeStartDocument();
            writer.writeCharacters("\n"); // Add a newline for pretty printing
            // Start the root element
            writer.writeStartElement("Book");
            writer.writeCharacters("\n");
            // Write child elements
            writeElement(writer, "title", "Effective Java");
            writeElement(writer, "author", "Joshua Bloch");
            writeElement(writer, "price", "45.99");
            // End the root element
            writer.writeEndElement();
            writer.writeCharacters("\n");
            // End the document
            writer.writeEndDocument();
        } finally {
            // Always close the writer
            writer.close();
        }
        String xmlString = stringWriter.toString();
        System.out.println(xmlString);
    }
    private static void writeElement(XMLStreamWriter writer, String tagName, String content) throws XMLStreamException {
        writer.writeCharacters("  "); // Indentation
        writer.writeStartElement(tagName);
        writer.writeCharacters(content);
        writer.writeEndElement();
        writer.writeCharacters("\n");
    }
}

Output:

Java XML如何高效转String?-图3
(图片来源网络,侵删)
<?xml version="1.0" ?><Book>Effective Java</title>
  <author>Joshua Bloch</author>
  <price>45.99</price>
</Book>

Using SAX (Simple API for XML) - Not Recommended for Generation

SAX is an event-driven parser, primarily for reading large XML files. It's not designed for generating XML strings, as it would be extremely complex and verbose to manually fire events to build a string. You should avoid using SAX for this task. Use DOM for small, in-memory generation or StAX for streaming generation.

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