杰瑞科技汇

Java字符串如何转为XML?

Of course! Converting a Java String to XML can mean a few different things. I'll cover the most common scenarios, from basic parsing to validation and generation.

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

Here's a breakdown of the approaches:

  1. Parsing a String into an XML Document Object (DOM): This is the most common task. You have a string containing XML and you want to load it into a structured, navigable object model in memory.
  2. Parsing with Validation: You want to ensure the string not only is well-formed XML but also adheres to a predefined schema (like XSD).
  3. Generating XML from Scratch: You have data in Java objects and want to create an XML string from it.
  4. Writing to a File: A common variation of the above, where you write the generated XML string to a file.

Scenario 1: Parsing a String into a DOM Document (Most Common)

This is the standard way to work with XML in Java. We'll use the built-in javax.xml.parsers package, which is part of Java's standard library (JAXP).

Key Classes:

  • DocumentBuilderFactory: Creates a parser factory.
  • DocumentBuilder: The actual parser that turns a source (like a string) into a Document.
  • Document: The in-memory tree representation of your XML (the DOM).
  • InputSource: A wrapper that can provide an XML document from various sources, including a StringReader.

Example Code:

Let's say you have this XML string:

<?xml version="1.0" encoding="UTF-8"?>
<library>
    <book id="101">
        <title>The Lord of the Rings</title>
        <author>J.R.R. Tolkien</author>
    </book>
    <book id="102">
        <title>Dune</title>
        <author>Frank Herbert</author>
    </book>
</library>

Here's the Java code to parse it:

Java字符串如何转为XML?-图2
(图片来源网络,侵删)
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
public class StringToXmlParser {
    public static void main(String[] args) {
        String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + "<library>"
                + "    <book id=\"101\">"
                + "        <title>The Lord of the Rings</title>"
                + "        <author>J.R.R. Tolkien</author>"
                + "    </book>"
                + "    <book id=\"102\">"
                + "        <title>Dune</title>"
                + "        <author>Frank Herbert</author>"
                + "    </book>"
                + "</library>";
        try {
            // 1. Create a DocumentBuilderFactory
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 2. Create a DocumentBuilder
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 3. Parse the XML string using an InputSource
            // We wrap the string in a StringReader and then in an InputSource
            Document document = builder.parse(new InputSource(new StringReader(xmlString)));
            // 4. Now you can work with the Document object
            System.out.println("Root element: " + document.getDocumentElement().getNodeName());
            // Get all book elements
            NodeList bookNodes = document.getElementsByTagName("book");
            System.out.println("\nFound " + bookNodes.getLength() + " books:");
            for (int i = 0; i < bookNodes.getLength(); i++) {
                Element book = (Element) bookNodes.item(i);
                String id = book.getAttribute("id");
                String title = book.getElementsByTagName("title").item(0).getTextContent();
                String author = book.getElementsByTagName("author").item(0).getTextContent();
                System.out.println("  Book ID: " + id);
                System.out.println("  Title: " + title);
                System.out.println("  Author: " + author);
                System.out.println("--------------------");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

Root element: library
Found 2 books:
  Book ID: 101 The Lord of the Rings
  Author: J.R.R. Tolkien
--------------------
  Book ID: 102 Dune
  Author: Frank Herbert
--------------------

Scenario 2: Parsing with Validation (Against an XSD Schema)

If your XML must conform to a specific structure (e.g., for an API), you should validate it against an XML Schema Definition (XSD).

Example XSD Schema (library.xsd):

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="library">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="book" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element type="xs:string" name="title"/>
                            <xs:element type="xs:string" name="author"/>
                        </xs:sequence>
                        <xs:attribute type="xs:int" name="id" use="required"/>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

Modified Java Code for Validation:

We need to enable schema validation on the DocumentBuilderFactory.

import org.w3c.dom.Document;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import java.io.File;
import java.io.StringReader;
import org.xml.sax.InputSource;
public class StringToXmlValidator {
    public static void main(String[] args) {
        String xmlString = "<library><book id=\"101\"><title>Valid Book</title><author>Valid Author</author></book></library>";
        String xsdPath = "library.xsd"; // Path to your XSD file
        try {
            // 1. Create a SchemaFactory and load the XSD
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(new File(xsdPath));
            // 2. Create a DocumentBuilderFactory and set the schema for validation
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setSchema(schema);
            factory.setNamespaceAware(true); // Important for schema validation
            // 3. Create a DocumentBuilder
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 4. Set an error handler to catch validation errors
            builder.setErrorHandler((e) -> {
                System.err.println("Validation Error: " + e.getMessage());
            });
            // 5. Parse the XML string
            Document document = builder.parse(new InputSource(new StringReader(xmlString)));
            System.out.println("XML is valid and parsed successfully!");
            System.out.println("Root element: " + document.getDocumentElement().getNodeName());
        } catch (Exception e) {
            // This will catch SAXParseException for validation errors
            System.err.println("Failed to parse or validate XML: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Scenario 3: Generating XML from Java Objects (String to XML in Reverse)

This is often done using a library like Jackson or JAXB (Java Architecture for XML Binding). JAXB is the standard but is now in the jakarta.xml.bind package since Java 9.

Java字符串如何转为XML?-图3
(图片来源网络,侵删)

Using JAXB (Standard Library)

Define your Java classes (POJOs) that map to XML elements:

import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;
@XmlRootElement // This maps the class to the root XML element
public class Library {
    private List<Book> books = new ArrayList<>();
    @XmlElement(name = "book") // This maps the list to <book> elements
    public List<Book> getBooks() {
        return books;
    }
    public void setBooks(List<Book> books) {
        this.books = books;
    }
}
class Book {
    private int id;
    private String title;
    private String author;
    @XmlElement
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    @XmlElement
    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; }
}

Use JAXB to convert an object to an XML string:

import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Marshaller;
import java.io.StringWriter;
public class JaxbXmlGenerator {
    public static void main(String[] args) throws Exception {
        // 1. Create the Java object
        Library library = new Library();
        Book book1 = new Book();
        book1.setId(101);
        book1.setTitle("The Hobbit");
        book1.setAuthor("J.R.R. Tolkien");
        library.getBooks().add(book1);
        Book book2 = new Book();
        book2.setId(102);
        book2.setTitle("1984");
        book2.setAuthor("George Orwell");
        library.getBooks().add(book2);
        // 2. Create JAXBContext
        JAXBContext context = JAXBContext.newInstance(Library.class);
        // 3. Create a Marshaller
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // Pretty print
        // 4. Marshal the object to a StringWriter
        StringWriter writer = new StringWriter();
        marshaller.marshal(library, writer);
        // 5. Get the XML string
        String xmlString = writer.toString();
        System.out.println(xmlString);
    }
}

Output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<library>
    <book>
        <id>101</id>
        <title>The Hobbit</title>
        <author>J.R.R. Tolkien</author>
    </book>
    <book>
        <id>102</id>
        <title>1984</title>
        <author>George Orwell</author>
    </book>
</library>

Summary: Which Approach to Use?

Goal Recommended Technology Why?
Parse an existing XML string javax.xml.parsers.DocumentBuilder (JAXP) Built into Java, standard, powerful for reading and navigating XML.
Parse XML with strict validation javax.xml.parsers.DocumentBuilder + XSD Schema Ensures your data conforms to a defined structure, preventing errors.
Generate XML from Java objects JAXB (jakarta.xml.bind) The standard, declarative way. Annotate your POJOs and let JAXB do the work.
Generate XML with complex control Jackson (com.fasterxml.jackson.dataformat) More flexible and powerful than JAXB, supports streaming (low memory).
Simple, custom XML generation String concatenation or StringBuilder Quick and dirty for very simple, static XML structures. Avoid for complex cases.
分享:
扫描分享到社交APP
上一篇
下一篇