Home » Xerces-J-src.2.9.1 » dom » [javadoc | source]

    1   /*
    2    * Licensed to the Apache Software Foundation (ASF) under one or more
    3    * contributor license agreements.  See the NOTICE file distributed with
    4    * this work for additional information regarding copyright ownership.
    5    * The ASF licenses this file to You under the Apache License, Version 2.0
    6    * (the "License"); you may not use this file except in compliance with
    7    * the License.  You may obtain a copy of the License at
    8    * 
    9    *      http://www.apache.org/licenses/LICENSE-2.0
   10    * 
   11    * Unless required by applicable law or agreed to in writing, software
   12    * distributed under the License is distributed on an "AS IS" BASIS,
   13    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   14    * See the License for the specific language governing permissions and
   15    * limitations under the License.
   16    */
   17   
   18   package dom;                    
   19   
   20   import java.io.IOException;
   21   import java.io.OutputStreamWriter;
   22   import java.io.PrintWriter;
   23   
   24   import org.apache.xerces.parsers.DOMParser;
   25   import org.apache.xerces.xni.Augmentations;
   26   import org.apache.xerces.xni.NamespaceContext;
   27   import org.apache.xerces.xni.QName;
   28   import org.apache.xerces.xni.XMLAttributes;
   29   import org.apache.xerces.xni.XMLLocator;
   30   import org.apache.xerces.xni.XMLString;
   31   import org.apache.xerces.xni.XNIException;
   32   import org.w3c.dom.Attr;
   33   import org.w3c.dom.Document;
   34   import org.w3c.dom.NamedNodeMap;
   35   import org.w3c.dom.Node;
   36   import org.w3c.dom.NodeList;
   37   
   38   /**
   39    * A sample of Adding lines to the DOM Node. This sample program illustrates:
   40    * - How to override methods from  DocumentHandler ( XMLDocumentHandler) 
   41    * - How to turn off ignorable white spaces by overriding ignorableWhiteSpace
   42    * - How to use the SAX Locator to return row position ( line number of DOM element).
   43    * - How to attach user defined Objects to Nodes using method setUserData
   44    * This example relies on the following:
   45    * - Turning off the "fast" DOM so we can use set expansion to FULL 
   46    * @version $Id: DOMAddLines.java 447683 2006-09-19 02:36:31Z mrglavas $
   47    */
   48   
   49   public class DOMAddLines extends DOMParser  {
   50   
   51      /** Print writer. */
   52      private PrintWriter out;
   53      static private boolean NotIncludeIgnorableWhiteSpaces = false;
   54      private XMLLocator locator; 
   55   
   56   
   57      public DOMAddLines( String inputName ) {
   58         //fNodeExpansion = FULL; // faster than: this.setFeature("http://apache.org/xml/features/defer-node-expansion", false);
   59   
   60         try {                        
   61            this.setFeature( "http://apache.org/xml/features/dom/defer-node-expansion", false ); 
   62            this.parse( inputName );
   63            out = new PrintWriter(new OutputStreamWriter(System.out, "UTF8"));
   64         } catch ( IOException e ) {
   65            System.err.println( "except" + e );
   66         } catch ( org.xml.sax.SAXException e ) {
   67            System.err.println( "except" + e );
   68         }
   69      } // constructor
   70   
   71      /** Prints the specified node, recursively. */
   72      public void print(Node node) {
   73         // is there anything to do?
   74         if ( node == null ) {
   75            return;
   76         }
   77   
   78         String lineRowColumn = (String ) ((Node) node).getUserData("startLine");
   79   
   80         int type = node.getNodeType();
   81         switch ( type ) {
   82            // print document
   83            case Node.DOCUMENT_NODE: {
   84                  out.println(  lineRowColumn + ":" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
   85                  print( ((Document)node).getDocumentElement());
   86                  out.flush();
   87                  break;
   88               }
   89   
   90               // print element with attributes
   91            case Node.ELEMENT_NODE: {
   92                  out.print( lineRowColumn + ":" + '<');
   93                  out.print(node.getNodeName());
   94                  Attr attrs[] = sortAttributes(node.getAttributes());
   95                  for ( int i = 0; i < attrs.length; i++ ) {
   96                     Attr attr = attrs[i];
   97                     out.print(' ');
   98                     out.print(attr.getNodeName());
   99                     out.print("=\"");
  100                     out.print( attr.getNodeValue());
  101                     out.print('"');
  102                  }
  103                  out.print('>');
  104                  NodeList children = node.getChildNodes();
  105                  if ( children != null ) {
  106                     int len = children.getLength();
  107                     for ( int i = 0; i < len; i++ ) {
  108                        print(children.item(i));
  109                     }
  110                  }
  111                  break;
  112               }
  113   
  114               // handle entity reference nodes
  115            case Node.ENTITY_REFERENCE_NODE: {
  116                  out.print('&');
  117                  out.print(node.getNodeName());
  118                  out.print(';');
  119                  break;
  120               }
  121   
  122               // print cdata sections
  123            case Node.CDATA_SECTION_NODE: {
  124                  out.print("<![CDATA[");
  125                  out.print(node.getNodeValue());
  126                  out.print("]]>");
  127                  break;
  128               }
  129   
  130               // print text
  131            case Node.TEXT_NODE: {
  132                  out.print(  node.getNodeValue());
  133                  break;
  134               }
  135   
  136               // print processing instruction
  137            case Node.PROCESSING_INSTRUCTION_NODE: {
  138                  out.print("<?");
  139                  out.print(node.getNodeName());
  140                  String data = node.getNodeValue();
  141                  if ( data != null && data.length() > 0 ) {
  142                     out.print(' ');
  143                     out.print(data);
  144                  }
  145                  out.print("?>");
  146                  break;
  147               }
  148         }
  149   
  150         if ( type == Node.ELEMENT_NODE ) {
  151            out.print("</");
  152            out.print(node.getNodeName());
  153            out.print('>');
  154         }
  155   
  156         out.flush();
  157   
  158      } // print(Node)
  159   
  160   
  161      /** Returns a sorted list of attributes. */
  162      private Attr[] sortAttributes(NamedNodeMap attrs) {
  163   
  164         int len = (attrs != null) ? attrs.getLength() : 0;
  165         Attr array[] = new Attr[len];
  166         for ( int i = 0; i < len; i++ ) {
  167            array[i] = (Attr)attrs.item(i);
  168         }
  169         for ( int i = 0; i < len - 1; i++ ) {
  170            String name  = array[i].getNodeName();
  171            int    index = i;
  172            for ( int j = i + 1; j < len; j++ ) {
  173               String curName = array[j].getNodeName();
  174               if ( curName.compareTo(name) < 0 ) {
  175                  name  = curName;
  176                  index = j;
  177               }
  178            }
  179            if ( index != i ) {
  180               Attr temp    = array[i];
  181               array[i]     = array[index];
  182               array[index] = temp;
  183            }
  184         }
  185   
  186         return (array);
  187   
  188      } // sortAttributes(NamedNodeMap):Attr[]
  189   
  190      /* Methods that we override */
  191   
  192      /*   We override startElement callback  from DocumentHandler */
  193   
  194      public void startElement(QName elementQName, XMLAttributes attrList, Augmentations augs) 
  195       throws XNIException {
  196         super.startElement(elementQName, attrList, augs);
  197   
  198         Node node = null;
  199         try {
  200         node = (Node) this.getProperty( "http://apache.org/xml/properties/dom/current-element-node" );
  201         //System.out.println( "The node = " + node );  TODO JEFF
  202         }
  203         catch( org.xml.sax.SAXException ex )
  204         {
  205             System.err.println( "except" + ex );;
  206         }
  207         if( node != null )
  208             node.setUserData( "startLine", String.valueOf( locator.getLineNumber() ), null ); // Save location String into node
  209      } //startElement 
  210   
  211      /* We override startDocument callback from DocumentHandler */
  212   
  213      public void startDocument(XMLLocator locator, String encoding, 
  214                                NamespaceContext namespaceContext, Augmentations augs) throws XNIException {
  215        super.startDocument(locator, encoding, namespaceContext, augs);
  216        this.locator = locator;
  217        Node node = null ;
  218         try {
  219         node = (Node) this.getProperty( "http://apache.org/xml/properties/dom/current-element-node" );
  220         }
  221        catch( org.xml.sax.SAXException ex )
  222         {
  223           System.err.println( "except" + ex );;
  224         }
  225        
  226        if( node != null )
  227             node.setUserData( "startLine", String.valueOf( locator.getLineNumber() ), null ); // Save location String into node
  228     } //startDocument 
  229      
  230   
  231      public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException
  232       {
  233       if(! NotIncludeIgnorableWhiteSpaces )
  234          super.ignorableWhitespace( text, augs);
  235       else
  236          ;// Ignore ignorable white spaces
  237       }// ignorableWhitespace
  238      
  239   
  240   
  241      //
  242      // Main
  243      //
  244   
  245      /** Main program entry point. */
  246      public static void main(String argv[]) {
  247         // is there anything to do?
  248         if ( argv.length == 0 ) {
  249            printUsage();
  250            System.exit(1);
  251         }
  252         // check parameters
  253   
  254         for ( int i = 0; i < argv.length; i++ ) {
  255            String arg = argv[i];
  256   
  257            // options
  258            if ( arg.startsWith("-") ) {
  259               if ( arg.equals("-h") ) {
  260                  printUsage();
  261                  System.exit(1);
  262               }
  263               if (arg.equals("-i")) {
  264                      NotIncludeIgnorableWhiteSpaces = true;
  265                      continue;
  266                  }
  267               
  268            }
  269         // DOMAddLine parse and print
  270   
  271         DOMAddLines domAddExample = new DOMAddLines( arg );
  272         Document doc             = domAddExample.getDocument();
  273         domAddExample.print( doc );
  274   
  275        }
  276      } // main(String[])
  277   
  278      /** Prints the usage. */
  279      private static void printUsage() {
  280         System.err.println("usage: jre dom.DOMAddLines (options) uri ...");
  281         System.err.println();
  282         System.err.println("  -h       Display help screen.");
  283         System.err.println("  -i       Don't print ignorable white spaces.");
  284   
  285      } // printUsage()
  286   
  287   }

Home » Xerces-J-src.2.9.1 » dom » [javadoc | source]