Differences
This shows you the differences between two versions of the page.
pretty_print_xml [2014/03/06 10:23] |
pretty_print_xml [2021/04/05 11:23] (current) |
||
---|---|---|---|
Line 1: | Line 1: | ||
+ | ====== Pretty Print XML in Java ====== | ||
+ | There are several ways to pretty print XML in Java. | ||
+ | ===== Using Xerces ===== | ||
+ | <sxh java> | ||
+ | public static String format(String unformattedXml) { | ||
+ | try { | ||
+ | final Document document = parseXml(unformattedXml); | ||
+ | |||
+ | OutputFormat format = new OutputFormat(document); | ||
+ | format.setLineWidth(65); | ||
+ | format.setIndenting(true); | ||
+ | format.setIndent(2); | ||
+ | Writer out = new StringWriter(); | ||
+ | XMLSerializer serializer = new XMLSerializer(out, | ||
+ | serializer.serialize(document); | ||
+ | |||
+ | return out.toString(); | ||
+ | } catch (IOException e) { | ||
+ | throw new RuntimeException(e); | ||
+ | } | ||
+ | } | ||
+ | |||
+ | private static Document parseXml(String in) { | ||
+ | try { | ||
+ | DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); | ||
+ | DocumentBuilder db = dbf.newDocumentBuilder(); | ||
+ | InputSource is = new InputSource(new StringReader(in)); | ||
+ | return db.parse(is); | ||
+ | } catch (ParserConfigurationException e) { | ||
+ | throw new RuntimeException(e); | ||
+ | } catch (SAXException e) { | ||
+ | throw new RuntimeException(e); | ||
+ | } catch (IOException e) { | ||
+ | throw new RuntimeException(e); | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | ===== Using Standard Java Library ===== | ||
+ | <sxh java> | ||
+ | public static String prettyFormat(String input, int indent) { | ||
+ | try { | ||
+ | Source xmlInput = new StreamSource(new StringReader(input)); | ||
+ | StringWriter stringWriter = new StringWriter(); | ||
+ | StreamResult xmlOutput = new StreamResult(stringWriter); | ||
+ | TransformerFactory transformerFactory = TransformerFactory.newInstance(); | ||
+ | transformerFactory.setAttribute(" | ||
+ | Transformer transformer = transformerFactory.newTransformer(); | ||
+ | transformer.setOutputProperty(OutputKeys.INDENT, | ||
+ | transformer.transform(xmlInput, | ||
+ | return xmlOutput.getWriter().toString(); | ||
+ | } catch (Exception e) { | ||
+ | throw new RuntimeException(e); | ||
+ | } | ||
+ | } | ||
+ | |||
+ | public static String prettyFormat(String input) { | ||
+ | return prettyFormat(input, | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | From http:// | ||
+ | |||
+ | {{tag> |