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();
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!