Java tutorial
//package com.java2s; //License from project: Open Source License import org.w3c.dom.*; public class Main { @SuppressWarnings({ "ChainOfInstanceofChecks" }) private static void formatElementStart(/*@Nonnull*/Document document, /*@Nonnull*/Element element, /*@Nonnull*/ String formatString) { Node previousSibling = element.getPreviousSibling(); if (previousSibling == null || previousSibling instanceof Element) { element.getParentNode().insertBefore(document.createTextNode(formatString), element); } else if (previousSibling instanceof Text) { Text textNode = (Text) previousSibling; String text = textNode.getWholeText(); if (!formatString.equals(text)) { textNode.replaceWholeText(trimRight(text) + formatString); } } } private static String trimRight(/*@Nullable*/String s) { if (s == null) { return null; } int lastIndex = s.length() - 1; int index = lastIndex; while (index >= 0 && s.charAt(index) <= ' ') { --index; } return index == lastIndex ? s : s.substring(0, index + 1); } }