FileDocCategorySizeDatePackage
DOMWriter.javaAPI DocApache Tomcat 6.0.1411164Fri Jul 20 04:20:34 BST 2007org.apache.catalina.util

DOMWriter

public class DOMWriter extends Object
A sample DOM writer. This sample program illustrates how to traverse a DOM tree in order to print a document that is parsed.

Fields Summary
private static String
PRINTWRITER_ENCODING
Default Encoding
private static String[]
MIME2JAVA_ENCODINGS
private boolean
qualifiedNames
Output qualified names
protected PrintWriter
out
Print writer.
protected boolean
canonical
Canonical output.
Constructors Summary
public DOMWriter(String encoding, boolean canonical)



       
     
      out = new PrintWriter(new OutputStreamWriter(System.out, encoding));
      this.canonical = canonical;
   
public DOMWriter(boolean canonical)
Default constructor.

      this( getWriterEncoding(), canonical);
   
public DOMWriter(Writer writer, boolean canonical)

        out = new PrintWriter(writer);
        this.canonical = canonical;
    
Methods Summary
public booleangetQualifiedNames()

      return this.qualifiedNames;
   
public static java.lang.StringgetWriterEncoding()

      return (PRINTWRITER_ENCODING);
   
public static booleanisValidJavaEncoding(java.lang.String encoding)

      for ( int i = 0; i < MIME2JAVA_ENCODINGS.length; i++ )
         if ( encoding.equals( MIME2JAVA_ENCODINGS[i] ) )
            return (true);

      return (false);
   
protected java.lang.Stringnormalize(java.lang.String s)
Normalizes the given string.

      StringBuffer str = new StringBuffer();

      int len = (s != null) ? s.length() : 0;
      for ( int i = 0; i < len; i++ ) {
         char ch = s.charAt(i);
         switch ( ch ) {
            case '<": {
                  str.append("<");
                  break;
               }
            case '>": {
                  str.append(">");
                  break;
               }
            case '&": {
                  str.append("&");
                  break;
               }
            case '"": {
                  str.append(""");
                  break;
               }
            case '\r":
            case '\n": {
                  if ( canonical ) {
                     str.append("&#");
                     str.append(Integer.toString(ch));
                     str.append(';");
                     break;
                  }
                  // else, default append char
               }
            default: {
                  str.append(ch);
               }
         }
      }

      return (str.toString());

   
public voidprint(org.w3c.dom.Node node)
Prints the specified node, recursively.


      // is there anything to do?
      if ( node == null ) {
         return;
      }

      int type = node.getNodeType();
      switch ( type ) {
         // print document
         case Node.DOCUMENT_NODE: {
               if ( !canonical ) {
                  String  Encoding = getWriterEncoding();
                  if( Encoding.equalsIgnoreCase( "DEFAULT" ) )
                     Encoding = "UTF-8";
                  else if( Encoding.equalsIgnoreCase( "Unicode" ) )
                     Encoding = "UTF-16";
                  else
                     Encoding = MIME2Java.reverse( Encoding );

                  out.println("<?xml version=\"1.0\" encoding=\""+
                           Encoding + "\"?>");
               }
               print(((Document)node).getDocumentElement());
               out.flush();
               break;
            }

            // print element with attributes
         case Node.ELEMENT_NODE: {
               out.print('<");
               if (this.qualifiedNames) { 
                  out.print(node.getNodeName());
               } else {
                  out.print(node.getLocalName());
               }
               Attr attrs[] = sortAttributes(node.getAttributes());
               for ( int i = 0; i < attrs.length; i++ ) {
                  Attr attr = attrs[i];
                  out.print(' ");
                  if (this.qualifiedNames) {
                     out.print(attr.getNodeName());
                  } else {
                     out.print(attr.getLocalName());
                  }
                  
                  out.print("=\"");
                  out.print(normalize(attr.getNodeValue()));
                  out.print('"");
               }
               out.print('>");
               NodeList children = node.getChildNodes();
               if ( children != null ) {
                  int len = children.getLength();
                  for ( int i = 0; i < len; i++ ) {
                     print(children.item(i));
                  }
               }
               break;
            }

            // handle entity reference nodes
         case Node.ENTITY_REFERENCE_NODE: {
               if ( canonical ) {
                  NodeList children = node.getChildNodes();
                  if ( children != null ) {
                     int len = children.getLength();
                     for ( int i = 0; i < len; i++ ) {
                        print(children.item(i));
                     }
                  }
               } else {
                  out.print('&");
                  if (this.qualifiedNames) {
                     out.print(node.getNodeName());
                  } else {
                     out.print(node.getLocalName());
                  }
                  out.print(';");
               }
               break;
            }

            // print cdata sections
         case Node.CDATA_SECTION_NODE: {
               if ( canonical ) {
                  out.print(normalize(node.getNodeValue()));
               } else {
                  out.print("<![CDATA[");
                  out.print(node.getNodeValue());
                  out.print("]]>");
               }
               break;
            }

            // print text
         case Node.TEXT_NODE: {
               out.print(normalize(node.getNodeValue()));
               break;
            }

            // print processing instruction
         case Node.PROCESSING_INSTRUCTION_NODE: {
               out.print("<?");
               if (this.qualifiedNames) {
                  out.print(node.getNodeName());
               } else {
                  out.print(node.getLocalName());
               }
               
               String data = node.getNodeValue();
               if ( data != null && data.length() > 0 ) {
                  out.print(' ");
                  out.print(data);
               }
               out.print("?>");
               break;
            }
      }

      if ( type == Node.ELEMENT_NODE ) {
         out.print("</");
         if (this.qualifiedNames) {
            out.print(node.getNodeName());
         } else {
            out.print(node.getLocalName());
         }
         out.print('>");
      }

      out.flush();

   
private static voidprintValidJavaEncoding()

      System.err.println( "    ENCODINGS:" );
      System.err.print( "   " );
      for( int i = 0;
                     i < MIME2JAVA_ENCODINGS.length; i++) {
         System.err.print( MIME2JAVA_ENCODINGS[i] + " " );
      if( (i % 7 ) == 0 ){
         System.err.println();
         System.err.print( "   " );
         }
      }

   
public voidsetQualifiedNames(boolean qualifiedNames)

      this.qualifiedNames = qualifiedNames;
   
public static voidsetWriterEncoding(java.lang.String encoding)

      if( encoding.equalsIgnoreCase( "DEFAULT" ) )
         PRINTWRITER_ENCODING  = "UTF8";
      else if( encoding.equalsIgnoreCase( "UTF-16" ) )
         PRINTWRITER_ENCODING  = "Unicode";
      else
         PRINTWRITER_ENCODING = MIME2Java.convert( encoding );
   
protected org.w3c.dom.Attr[]sortAttributes(org.w3c.dom.NamedNodeMap attrs)
Returns a sorted list of attributes.


      int len = (attrs != null) ? attrs.getLength() : 0;
      Attr array[] = new Attr[len];
      for ( int i = 0; i < len; i++ ) {
         array[i] = (Attr)attrs.item(i);
      }
      for ( int i = 0; i < len - 1; i++ ) {
         String name = null;
         if (this.qualifiedNames) {
            name  = array[i].getNodeName();
         } else {
            name  = array[i].getLocalName();
         }
         int    index = i;
         for ( int j = i + 1; j < len; j++ ) {
            String curName = null;
            if (this.qualifiedNames) {
               curName = array[j].getNodeName();
            } else {
               curName = array[j].getLocalName();
            }
            if ( curName.compareTo(name) < 0 ) {
               name  = curName;
               index = j;
            }
         }
         if ( index != i ) {
            Attr temp    = array[i];
            array[i]     = array[index];
            array[index] = temp;
         }
      }

      return (array);