pretty-print xml in java (#11899)
* pretty-print xml in java * simplified pom.xml
This commit is contained in:
parent
612dc0be7c
commit
d30c353d35
1
pom.xml
1
pom.xml
|
@ -1206,6 +1206,7 @@
|
|||
<module>wicket</module>
|
||||
<module>wildfly</module>
|
||||
<module>xml</module>
|
||||
<module>xml-2</module>
|
||||
<module>xstream</module>
|
||||
</modules>
|
||||
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
xml/.idea
|
|
@ -0,0 +1,5 @@
|
|||
## XML
|
||||
|
||||
This module contains articles about eXtensible Markup Language (XML)
|
||||
|
||||
### Relevant Articles:
|
|
@ -0,0 +1,50 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>xml-2</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>xml-2</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- xml libraries -->
|
||||
<dependency>
|
||||
<groupId>org.dom4j</groupId>
|
||||
<artifactId>dom4j</artifactId>
|
||||
<version>${dom4j.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>xml-2</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
<properties>
|
||||
<dom4j.version>2.1.3</dom4j.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,91 @@
|
|||
package com.baeldung.xml.prettyprint;
|
||||
|
||||
import org.dom4j.DocumentHelper;
|
||||
import org.dom4j.io.OutputFormat;
|
||||
import org.dom4j.io.XMLWriter;
|
||||
import org.w3c.dom.Document;
|
||||
import org.xml.sax.InputSource;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.transform.OutputKeys;
|
||||
import javax.xml.transform.Transformer;
|
||||
import javax.xml.transform.TransformerFactory;
|
||||
import javax.xml.transform.dom.DOMSource;
|
||||
import javax.xml.transform.stream.StreamResult;
|
||||
import javax.xml.transform.stream.StreamSource;
|
||||
import java.io.*;
|
||||
|
||||
public class XmlPrettyPrinter {
|
||||
|
||||
public static String prettyPrintByTransformer(String xmlString, int indent, boolean ignoreDeclaration) {
|
||||
|
||||
try {
|
||||
final InputSource src = new InputSource(new StringReader(xmlString));
|
||||
final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src);
|
||||
|
||||
TransformerFactory transformerFactory = TransformerFactory.newInstance();
|
||||
transformerFactory.setAttribute("indent-number", indent);
|
||||
Transformer transformer = transformerFactory.newTransformer(new StreamSource(new StringReader(readPrettyPrintXslt())));
|
||||
// Using the default transformer will create empty lines in Java9+
|
||||
// Transformer transformer = transformerFactory.newTransformer();
|
||||
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
|
||||
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ignoreDeclaration ? "yes" : "no");
|
||||
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||
// Alternatively, we can set indent-size on the transformer object
|
||||
// transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
|
||||
Writer out = new StringWriter();
|
||||
transformer.transform(new DOMSource(document), new StreamResult(out));
|
||||
return out.toString();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Error occurs when pretty-printing xml:\n" + xmlString, e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static String prettyPrintByDom4j(String xmlString, int indent, boolean skipDeclaration) {
|
||||
try {
|
||||
final OutputFormat format = OutputFormat.createPrettyPrint();
|
||||
format.setEncoding("UTF-8");
|
||||
format.setIndentSize(indent);
|
||||
format.setSuppressDeclaration(skipDeclaration);
|
||||
|
||||
final org.dom4j.Document document = DocumentHelper.parseText(xmlString);
|
||||
final StringWriter sw = new StringWriter();
|
||||
final XMLWriter writer = new XMLWriter(sw, format);
|
||||
writer.write(document);
|
||||
return sw.toString();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Error occurs when pretty-printing xml:\n" + xmlString, e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
InputStream inputStream = XmlPrettyPrinter.class.getResourceAsStream("/xml/emails.xml");
|
||||
String xmlString = readFromInputStream(inputStream);
|
||||
System.out.println("Pretty printing by Transformer");
|
||||
System.out.println("=============================================");
|
||||
System.out.println(prettyPrintByTransformer(xmlString, 2, true));
|
||||
System.out.println("=============================================");
|
||||
System.out.println("Pretty printing by Dom4j");
|
||||
System.out.println("=============================================");
|
||||
System.out.println(prettyPrintByDom4j(xmlString, 8, false));
|
||||
System.out.println("=============================================");
|
||||
}
|
||||
|
||||
|
||||
private static String readPrettyPrintXslt() throws IOException {
|
||||
InputStream inputStream = XmlPrettyPrinter.class.getResourceAsStream("/xml/prettyprint.xsl");
|
||||
return readFromInputStream(inputStream);
|
||||
}
|
||||
|
||||
private static String readFromInputStream(InputStream inputStream) throws IOException {
|
||||
StringBuilder resultStringBuilder = new StringBuilder();
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
|
||||
String line;
|
||||
while ((line = br.readLine()) != null) {
|
||||
resultStringBuilder.append(line).append("\n");
|
||||
}
|
||||
}
|
||||
return resultStringBuilder.toString();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
|
@ -0,0 +1,4 @@
|
|||
<emails> <email> <from>Kai</from> <to>Amanda</to> <time>2018-03-05</time>
|
||||
<subject>I am flying to you</subject></email> <email>
|
||||
<from>Jerry</from> <to>Tom</to> <time>1992-08-08</time> <subject>Hey Tom, catch me if you can!</subject>
|
||||
</email> </emails>
|
|
@ -0,0 +1,11 @@
|
|||
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
|
||||
<xsl:strip-space elements="*"/>
|
||||
<xsl:output method="xml" encoding="UTF-8"/>
|
||||
|
||||
<xsl:template match="@*|node()">
|
||||
<xsl:copy>
|
||||
<xsl:apply-templates select="@*|node()"/>
|
||||
</xsl:copy>
|
||||
</xsl:template>
|
||||
|
||||
</xsl:stylesheet>
|
Loading…
Reference in New Issue