Pretty Printing XML in Java
Given a Java String containing unformatted XML, the objective is to transform it into a well-structured XML String with proper line breaks and indentation.
Solution:
Instantiate a Transformer:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Set Output Properties:
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
Create a StreamResult for Output:
StreamResult result = new StreamResult(new StringWriter());
Create a DOMSource for the Input String:
DOMSource source = new DOMSource(doc);
Transform Source to Result:
transformer.transform(source, result);
Retrieve Formatted XML String:
String xmlString = result.getWriter().toString();
Code Example:
String unformattedXml = ""; 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 formattedXml = result.getWriter().toString(); System.out.println(formattedXml); hello
Note: The specific results may vary depending on the Java version used. Modifications might be necessary to cater to specific platforms.
The above is the detailed content of How to Pretty Print XML in Java Using XSLT?. For more information, please follow other related articles on the PHP Chinese website!