Home > Java > javaTutorial > How to Format Unformatted XML Strings in Java?

How to Format Unformatted XML Strings in Java?

Mary-Kate Olsen
Release: 2024-12-22 02:34:27
Original
853 people have browsed it

How to Format Unformatted XML Strings in Java?

Formatting XML Strings in Java

You have an unformatted XML string in Java and need to transform it into a readable, indented format. To achieve this, a series of steps are required:

Create a new Transformer instance using TransformerFactory.newInstance().newTransformer().

Configure the Transformer by setting the OutputKeys.INDENT property to "yes" and specifying the indentation amount using the {http://xml.apache.org/xslt}indent-amount property.

Parse the unformatted XML string into a Document Object Model (DOM) using an XML parser.

Create a DOMSource object using the parsed DOM.

Use the StreamResult object to capture the formatted XML as a string.

Apply the Transformer transformation to the DOMSource, writing the result to the StreamResult.

Finally, you will obtain the formatted XML as a string by calling result.getWriter().toString().

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
Copy after login

Note that the doc variable refers to a parsed XML document that is not shown in the provided code snippet.

The above is the detailed content of How to Format Unformatted XML Strings in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template