/** Reflow XML */ public void doFormat() { Vector parts = new Vector(); char[] chars = original.toCharArray(); int index = 0; int first = 0; String part = null; while (index < chars.length) { // Check for start of tag if (chars[index] == '<') { // Did we have data before this tag? if (first < index) { part = new String(chars, first, index - first); part = part.trim(); // Save non-whitespace data if (part.length() > 0) { parts.addElement(part); } } // Save the start of tag first = index; } // Check for end of tag if (chars[index] == '>') { // Save the tag part = new String(chars, first, index - first + 1); parts.addElement(part); first = index + 1; } // Check for end of line if ((chars[index] == '\n') || (chars[index] == '\r')) { // Was there data on this line? if (first < index) { part = new String(chars, first, index - first); part = part.trim(); // Save non-whitespace data if (part.length() > 0) { parts.addElement(part); } } first = index + 1; } index++; } // Reflow as XML StringBuffer buf = new StringBuffer(); Object[] list = parts.toArray(); int indent = 0; int pad = 0; index = 0; while (index < list.length) { part = (String) list[index]; if (buf.length() == 0) { // Just add first tag (should be XML header) buf.append(part); } else { // All other parts need to start on a new line buf.append('\n'); // If we're at an end tag then decrease indent if (part.startsWith("</")) { indent--; } // Add any indent for (pad = 0; pad < indent; pad++) { buf.append(" "); } // Add the tag or data buf.append(part); // If this is a start tag then increase indent if (part.startsWith("<") && !part.startsWith("</") && !part.endsWith("/>")) { indent++; // Check for special <tag>data</tag> case if ((index + 2) < list.length) { part = (String) list[index + 2]; if (part.startsWith("</")) { part = (String) list[index + 1]; if (!part.startsWith("<")) { buf.append(part); part = (String) list[index + 2]; buf.append(part); index = index + 2; indent--; } } } } } index++; } formatted = new String(buf); }