@@ -47,36 +47,25 @@ public static String prettyPrintXML(String input) throws TransformerConfiguratio
47
47
transformer .setOutputProperty (OutputKeys .INDENT , "yes" );
48
48
transformer .setOutputProperty ("{http://xml.apache.org/xslt}indent-amount" , Integer .toString (IDENT_AMOUNT ));
49
49
transformer .setOutputProperty (OutputKeys .OMIT_XML_DECLARATION , "yes" );
50
-
51
50
StreamResult result = new StreamResult (new StringWriter ());
52
51
Document doc = DocumentBuilderFactory .newInstance ().newDocumentBuilder ()
53
52
.parse (new InputSource (new StringReader (input )));
54
-
55
- // XPath for selecting all text contents
56
- XPathExpression xpath = XPathFactory .newInstance ().newXPath ().compile ("//*[text()]/*" );
57
- // this is better but it does not work, because the default java xpath
58
- // transformer does not support XPath 2.0
59
- // XPathExpression xpath =
60
- // XPathFactory.newInstance().newXPath().compile("//*[text()[matches(.,'^[0-9A-F ]*$')]]");
61
- // XPath for counting the number of ancestors of a current element
53
+ XPathExpression xpath = XPathFactory .newInstance ().newXPath ().compile ("//*[count(./*) = 0]" );
62
54
XPathExpression xpathDepth = XPathFactory .newInstance ().newXPath ().compile ("count(ancestor-or-self::*)" );
63
55
64
56
NodeList textNodes = (NodeList ) xpath .evaluate (doc , XPathConstants .NODESET );
65
57
66
58
for (int i = 0 ; i < textNodes .getLength (); i ++) {
67
59
String content = textNodes .item (i ).getTextContent ();
68
- System .out .println (textNodes .item (i ).getTextContent ());
69
60
double doubleDepth = (Double ) xpathDepth .evaluate (textNodes .item (i ), XPathConstants .NUMBER );
70
61
int depth = (int ) doubleDepth ;
71
62
String emptyString = createEmptyString (depth );
72
- System .out .println (depth );
73
63
String newContent = content .replaceAll ("\n " , ("\n " + emptyString ));
74
- // remove last white space elements from the text content to align
75
- // the closing tag
76
64
if (newContent .length () > content .length ()) {
77
65
newContent = newContent .substring (0 , newContent .length () - IDENT_AMOUNT );
78
66
}
79
67
textNodes .item (i ).setTextContent (newContent );
68
+
80
69
}
81
70
82
71
DOMSource source = new DOMSource (doc );
0 commit comments