Revision 45100
Added by Claudio Atzori almost 8 years ago
modules/cnr-misc-utils/trunk/src/main/java/eu/dnetlib/miscutils/functional/xml/IndentXmlString.java | ||
---|---|---|
1 | 1 |
package eu.dnetlib.miscutils.functional.xml; |
2 | 2 |
|
3 |
import java.io.IOException; |
|
4 |
import java.io.StringReader; |
|
5 |
import java.io.StringWriter; |
|
6 |
import java.io.Writer; |
|
3 |
import java.io.*; |
|
4 |
import java.nio.charset.Charset; |
|
7 | 5 |
|
8 | 6 |
import javax.xml.parsers.DocumentBuilder; |
9 | 7 |
import javax.xml.parsers.DocumentBuilderFactory; |
10 | 8 |
import javax.xml.parsers.ParserConfigurationException; |
9 |
import javax.xml.transform.*; |
|
10 |
import javax.xml.transform.dom.DOMResult; |
|
11 |
import javax.xml.transform.dom.DOMSource; |
|
12 |
import javax.xml.transform.stream.StreamResult; |
|
11 | 13 |
|
14 |
import org.apache.commons.lang.CharSetUtils; |
|
12 | 15 |
import org.w3c.dom.Document; |
13 | 16 |
import org.xml.sax.InputSource; |
14 | 17 |
import org.xml.sax.SAXException; |
... | ... | |
82 | 85 |
} |
83 | 86 |
} |
84 | 87 |
|
88 |
private String doIndent(final Document document) throws TransformerException, UnsupportedEncodingException { |
|
89 |
|
|
90 |
final Transformer transformer = getTransformer(); |
|
91 |
final ByteArrayOutputStream out = new ByteArrayOutputStream(); |
|
92 |
transformer.transform(new DOMSource(document), new StreamResult(out)); |
|
93 |
|
|
94 |
return out.toString("utf-8"); |
|
95 |
} |
|
96 |
|
|
97 |
private Transformer getTransformer() throws TransformerConfigurationException { |
|
98 |
TransformerFactory tf = TransformerFactory.newInstance(); |
|
99 |
Transformer transformer = tf.newTransformer(); |
|
100 |
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); |
|
101 |
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes"); |
|
102 |
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); |
|
103 |
return transformer; |
|
104 |
} |
|
105 |
|
|
106 |
private Document doIndentDocument(final Document document) throws TransformerException, UnsupportedEncodingException { |
|
107 |
|
|
108 |
final Transformer transformer = getTransformer(); |
|
109 |
|
|
110 |
final DOMResult out = new DOMResult(); |
|
111 |
transformer.transform(new DOMSource(document), out); |
|
112 |
|
|
113 |
return (Document) out.getNode(); |
|
114 |
} |
|
115 |
|
|
85 | 116 |
/** |
86 | 117 |
* Static helper Apply. |
87 | 118 |
* |
... | ... | |
93 | 124 |
return new IndentXmlString().evaluate(xml); |
94 | 125 |
} |
95 | 126 |
|
127 |
/** |
|
128 |
* Static helper Apply. |
|
129 |
* |
|
130 |
* @param xml |
|
131 |
* the xml |
|
132 |
* @return the indented xml string |
|
133 |
*/ |
|
134 |
public static Document apply(final Document xml) throws TransformerException, UnsupportedEncodingException { |
|
135 |
return new IndentXmlString().doIndentDocument(xml); |
|
136 |
} |
|
137 |
|
|
96 | 138 |
} |
Also available in: Unified diff
added xml indentation helpers