Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * This file is part of the DiffX library.
   *
   * For licensing information please see the file license.txt included in the release.
   * A copy of this licence can also be found at
   *   http://www.opensource.org/licenses/artistic-license-2.0.php
   */
  package com.topologi.diffx.xml;
  
 import java.io.Reader;
 import java.io.Writer;
 
 
A class to indent automatically some XML data.

Note: This implementation is not namespace aware, and will not handle entities other than &, <, > or ".

Author(s):
Christophe Lauret - Allette Systems (Australia)
Version:
26 February 2005
 
 public final class XMLIndenter extends DefaultHandler implements ContentHandler {

  
The writer where the XML goes.
 
   private final PrintWriter writer;
 
   // state attributes ---------------------------------------------------------------------------
 
  
The indentation level.
 
   private transient int indentLevel = 0;

  
The stack of states
 
   private transient Stack<Integerstates = new Stack<Integer>();

  
Element has neither text, nor children.
 
   private static final Integer EMPTY = new Integer(0);

  
Element has text.
 
   private static final Integer HAS_TEXT = new Integer(1);

  
Element has children.
 
   private static final Integer HAS_CHILDREN = new Integer(2);
 
   /* ----------------------------------------- constructor --------------------------------------- */

  
Creates a new XML Indenter.

Parameters:
w The writer to use.
 
   private XMLIndenter(Writer w) {
     if (w instanceof PrintWriter) {
       this. = (PrintWriterw;
     } else {
       this. = new PrintWriter(w);
     }
   }
 
   /* -------------------------------------- handler's methods ------------------------------------ */

  
 
   @Override
   public void startElement(String uriString localNameString qNameAttributes atts) {
     // update the state of previous element
     if (!this..empty()) {
       if (this..pop().equals()) {
         this..println('>');
       }
       this..push();
     }
    // always indent
    for (int i = 0; i < this.i++) {
      this..print("  ");
    }
    // print XML data
    this..print('<' + qName);
    for (int i = 0; i < atts.getLength(); i++) {
      this..print(' '+atts.getQName(i)+"=\""+atts.getValue(i)+'"');
    }
    // update attributes
    this.++;
    this..push();
  }

  
  public void endElement(String uriString localNameString qName) {
    this.--;
    Object state = this..pop();
    if (.equals(state)) {
      this..println("/>");
    } else if (.equals(state)) {
      this..println("</" + qName + '>');
    } else if (.equals(state)) {
      for (int i = 0; i < this.i++) {
        this..print("  ");
      }
      this..println("</" + qName + '>');
    }
  }

  
Prints the characters.
  public void characters(char[] chint positionint offset) {
    if (this..peek().equals()) {
      this..pop();
      this..print('>');
      this..push();
    }
    this..print(new String(chpositionoffset));
  }

  
Does nothing.
  public void ignorableWhitespace(char[] chint positionint offset) {
    // do nothing.
  }
  /* ---------------------------------------- static methods ------------------------------------- */

  
Indents the given XML String.

Parameters:
xml The XML string to indent
Returns:
The indented XML String.
Throws:
java.io.IOException If an IOException occurs.
org.xml.sax.SAXException If the XML is not well-formed.
javax.xml.parsers.ParserConfigurationException If the parser could not be configured
  public static String indent(String xml)
    Writer writer = new StringWriter();
    Reader reader = new StringReader(xml);
    indent(readerwriter);
    return writer.toString();
  }

  
Indents the given XML String.

Parameters:
r A reader on XML data
w A writer for the indented XML
Throws:
java.io.IOException If an IOException occurs.
org.xml.sax.SAXException If the XML is not well-formed.
javax.xml.parsers.ParserConfigurationException If the parser could not be configured
  public static void indent(Reader rWriter w)
    // create the indenter
    XMLIndenter indenter = new XMLIndenter(w);
    // initialise the SAX framework
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    InputSource source = new InputSource(r);
    // parse the XML
    XMLReader xmlreader = factory.newSAXParser().getXMLReader();
    xmlreader.setContentHandler(indenter);
    xmlreader.parse(source);
  }

  
Indents the given XML String.

Parameters:
xml The XML string to indent
Returns:
The indented XML String or null if an error occurred.
  public static String indentSilent(String xml) {
    try {
      return indent(xml);
    } catch (Exception ex) {
      return null;
    }
  }

  
Indents the given XML String.

This method does not throw any exception out of convenience, instead it returns a boolean value to indicate whether the XML indenting was performed succesfully.

Parameters:
r A reader on XML data
w A writer for the indented XML
Returns:
true if the operation was successful, false if an error occurred.
  public static boolean indentSilent(Reader rWriter w) {
    try {
      indent(rw);
      return true;
    } catch (Exception ex) {
      return false;
    }
  }
New to GrepCode? Check out our FAQ X