DocWriter has a static method for writing XML documents with a writer : DOM « XML « Java






DocWriter has a static method for writing XML documents with a writer

     
/**
 * Copyright (c) 2006-2010 Richard Rodgers
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//package com.monad.homerun.util;

import java.io.IOException;
import java.io.Writer;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * DocWriter has a static method for writing XML documents with a writer
 */
public class DocWriter
{
  // indentation constant: 2 spaces
    private static final String SINGLE_INDENT = " ";
    
    public static void writeNodeToStream(Node node, Writer out) throws IOException {
    serializeNode(node, out, "");
    out.write('\n');
    out.flush();
    }
    
    /**
     * Writes a document to a stream
     * 
     * @param doc
     *        the XML docuument to write
     * @param out
     *        the output stream to write to
     * @throws IOException
     */
    public static void writeDocToStream( Document doc, Writer out )
                                         throws IOException
  {
    serializeNode( doc, out, "" );
    out.write( '\n' );
    out.flush();
  }
    
    private static void serializeNode( Node node, Writer out, String indent ) throws IOException
    {
      switch ( node.getNodeType() )
    {
        case Node.DOCUMENT_NODE:
          out.write( "<?xml version=\"1.0\"?>" + '\n' );
          writeNode( ((Document)node).getDocumentElement(), out, indent );
          break;
        case Node.ELEMENT_NODE:
          writeNode( node, out, indent );
          break;
        case Node.TEXT_NODE:
          out.write( node.getNodeValue() );
          break;
        case Node.COMMENT_NODE:
          out.write( /*indent + */ "<!--" + node.getNodeValue() + "-->" );
          break;
        default:
          System.out.println( "Got node: " + node.getNodeName() );
          break;
    }
    }
         
    private static void writeNode( Node node, Writer out, String indent )
                                   throws IOException
    {
      out.write( nodeWithAttrs( node, indent ) );
      NodeList kids = node.getChildNodes();
      if ( kids != null )
      {
        if ( ( kids.item( 0 ) != null ) &&
           ( kids.item( 0 ).getNodeType() == Node.ELEMENT_NODE ) )
        {
          out.write( '\n' );
        }
        for ( int i = 0; i < kids.getLength(); i++ )
        {
          serializeNode( kids.item( i ), out, indent + SINGLE_INDENT );
        }
        /* RLR - bug in indent logic - seems to work OK without
           if ( ( kids.item( 0 ) != null ) &&
              ( kids.item( kids.getLength()-1).getNodeType() == Node.ELEMENT_NODE ) )
           {
             out.write( indent );
           }
           */
      }
      if ( node.hasChildNodes() )
      {
        /* indent bug - leave out
        if ( kids.item( 0 ) != null && kids.item( 0 ).getNodeType() == Node.ELEMENT_NODE )
        {
          out.write( indent );
        }
        */
        out.write( "</" + node.getNodeName() + ">" );
      }
    }
    
    private static String nodeWithAttrs( Node node, String indent )
    {
        StringBuffer sb = new StringBuffer();
        // indent bug - leave out
        //sb.append( indent );
        sb.append( "<" );
        sb.append( node.getNodeName() );

        NamedNodeMap attrs = node.getAttributes();
        for ( int i = 0; i < attrs.getLength(); i++ )
        {
            sb.append( " " );
            Node attrNode = attrs.item( i );
            sb.append( attrNode.getNodeName() );
            sb.append( "=\"" );
            sb.append( attrNode.getNodeValue() );
            sb.append( "\"" );
        }

        if ( ! node.hasChildNodes() )
        {
            sb.append( "/>" );
        }
        else
        {
            sb.append( ">" );
        }

        return sb.toString();
    }
}

   
    
    
    
    
  








Related examples in the same category

1.Parsing a Document Using JAXP
2.XML Document information by DOM
3.Using DOM for Syntax Checking
4.Using the DOM Parser to Build a Document TreeUsing the DOM Parser to Build a Document Tree
5.DOM FeaturesDOM Features
6.DOM level 2 EventsDOM level 2 Events
7.Searching through a document
8.Check a vendor's DOM implementationCheck a vendor's DOM implementation
9.Make up and write an XML document, using DOMMake up and write an XML document, using DOM
10.Creating XML Document using DOM
11.Loading an XML Document using DOM
12.Parse an XML string: Using DOM and a StringReader.
13.Create an XML document with DOM
14.Extracting an XML formatted string out of a DOM object
15.Reading an XML Document and create user-defined object from DOM
16.Visiting All the Nodes in a DOM Document
17.Generating SAX Parsing Events by Traversing a DOM Document
18.Converting an XML Fragment into a DOM Fragment
19.A utility class which provides methods for working with a W3C DOM
20.XML DOM Utilities
21.Convenience methods for working with the DOM API
22.DOM Utils
23.Utilities to read DOM
24.W3C DOM utility methods
25.Read XML as DOM
26.Utility method for parsing the XML with DOM
27.Handles DOM processing allowing the reading and writing of hierarchical structures as XML files.
28.Xml Utils for dom4j