XmlUtil { static int estimateIndentationSize(BufferedReader xml) throws IOException { boolean inComment = false; Map<Integer, Integer> indentHist = new HashMap<>(2); String line; int prevIndent = 0; int prevNonWhiteSpaceIdx = 0; while ((line = xml.readLine()) != null) { if (inComment) { if (line.contains("-->")) { inComment = false; } } else { int startCommentIdx = line.indexOf("<!--"); int endCommentIdx = line.indexOf("-->"); inComment = startCommentIdx >= 0 && endCommentIdx == -1; int nonWhitespaceIdx = -1; int maxCheckIdx = startCommentIdx >= 0 ? startCommentIdx : line.length(); for (int i = 0; i < maxCheckIdx; ++i) { if (!Character.isWhitespace(line.charAt(i))) { nonWhitespaceIdx = i; break; } } if (nonWhitespaceIdx == -1) { continue; } int indent = Math.abs(nonWhitespaceIdx - prevNonWhiteSpaceIdx); if (indent > 0) { indentHist.compute(indent, (x, count) -> count == null ? 1 : count + 1); prevIndent = indent; } else if (prevIndent != 0) { indentHist.compute(prevIndent, (x, count) -> count == null ? 1 : count + 1); } prevNonWhiteSpaceIdx = nonWhitespaceIdx; } } return indentHist.isEmpty() ? 2 : indentHist.entrySet().stream() .reduce(new SimpleEntry<>(0, 1), (a, b) -> a.getValue() > b.getValue() ? a : b) .getKey(); } private  XmlUtil();   }
@Test public void testIndentationSizeEstimation() throws Exception { String text = "a\n b\n c\n d"; assertEquals(2, XmlUtil.estimateIndentationSize(new BufferedReader(new StringReader(text)))); }