Apply some indent to some XML. - Java XML

Java examples for XML:XML String Output

Description

Apply some indent to some XML.

Demo Code

/*/* w  w  w . j  a v a2s  .co  m*/
 * Copyright (C) 2002-2015 FlyMine
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  See the LICENSE file for more
 * information or http://www.gnu.org/copyleft/lesser.html.
 *
 */
//package com.java2s;
import java.io.ByteArrayOutputStream;

public class Main {
    public static void main(String[] argv) throws Exception {
        String xmlString = "java2s.com";
        System.out.println(indentXmlSimple(xmlString));
    }

    /**
     * Apply some indent 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
     * any whitespace.
     *
     * @param xmlString input XML fragment
     * @return indented XML fragment
     */
    public static String indentXmlSimple(String xmlString) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        int indent = 0;
        byte[] bytes = xmlString.getBytes();
        int i = 0;
        while (i < bytes.length) {
            if (bytes[i] == '<' && bytes[i + 1] == '/') {
                os.write('\n');
                writeIndentation(os, --indent);
            } else if (bytes[i] == '<') {
                if (i > 0) {
                    os.write('\n');
                }
                writeIndentation(os, indent++);
            } else if (bytes[i] == '/' && bytes[i + 1] == '>') {
                indent--;
            } else if (bytes[i] == '>') {
                // assumes terminating tag
            }
            os.write(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 Tutorials