Apply some indentiation to some XML. : Transform « XML « Java

Apply some indentiation to some XML.

//package com.qlogic.commons.utils;


 * General-purpose methods for manipulating URIs and XML schema types
 * @author Mohammed LOUKILI
public class XmlUtil {
   * Apply some indentiation to some XML. This method is not very
   * sophisticated and will not cope well with anything but the simplest XML
   * (no CDATA etc). The algorithm used does not look at element names and
   * does not actually parse the XML. It also assumes that the forward slash
   * and greater-than at the end of a self-terminating tag and not seperated
   * by ant whitespace.
   * @param xmlString
   *            input XML fragment
   * @return indented XML fragment
  public static String indentXmlSimple(String xmlString) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    int indent = 0;
    char bytes[] = xmlString.toCharArray();
    int i = 0;
    while (i < bytes.length) {
      if (bytes[i] == '<' && bytes[i + 1] == '/') {
        writeIndentation(os, --indent);
      } else if (bytes[i] == '<') {
        if (i > 0) {
        writeIndentation(os, indent++);
      } else if (bytes[i] == '/' && bytes[i + 1] == '>') {
      } else if (bytes[i] == '>') {

    return os.toString();

  private static void writeIndentation(ByteArrayOutputStream os, int indent) {
    for (int j = 0; j < indent; j++) {
      os.write(' ');
      os.write(' ');


Related examples in the same category

1.XML transformation
2.A Program That Performs XML Transformations
4.Use the transform.TransformerFactory plugability in the JAXP API
5.Processing XML Documents Partially
6.Set the TransformerFactory system property to generate and use translets
7.Transforming DOM Node to HTML with JAXP
8.Transformer with parameters
9.Create an XML file and attach an XSL
10.Applying XSLT Stylesheets
11.Catch TransformerException
12.Formatting an XML file using Transformer
13.Transforming an XML File with XSL into a DOM Document
14.XML input, output and transform utilities
15.XSL transformations: It applies a transformation to a set of employee recordsXSL transformations: It applies a transformation to a set of employee records
16.How to write an XML file. It saves a file describing a modern drawing in SVG format.
17.Applies a stylesheet to a given xml document.
18.Applies a stylesheet (that receives parameters) to a given xml document.