You are viewing a plain text version of this content. The canonical link for it is here.
Posted to c-dev@xerces.apache.org by Charlie Hart <ch...@nc.rr.com> on 2001/01/12 20:26:31 UTC

domprint class

I know I can modify the DOMPrint sample program to dump a DOM tree in my
program. Has anyone written a class to do this that they can send me?
thanks...charlie


RE: domprint class

Posted by Linda Derezinski <li...@interfacecontrol.com>.
Hope this is what you are looking for
/*
 * (C) Copyright IBM Corp. 1999  All rights reserved.
 *
 * US Government User/\s Restricted Rights Use, duplication or
 * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
 *
 * The program is provided "as is" without any warranty express or
 * implied, including the warranty of non-infringement and the implied
 * warranties of merchantibility and fitness for a particular purpose.
 * IBM will not be liable for any damages suffered by you as a result
 * of using the Program. In no event will IBM be liable for any
 * special, indirect or consequential damages or lost profits even if
 * IBM has been advised of the possibility of their occurrence. IBM
 * will not be liable for any third party claims against you.
 *
 *
 *
 */

/**
** DOMWriter.java
**
** This file is taken from IBM sample code DOMWriter.java from build
xml4j_2_0_15
** It is simpler than the original source code
**
** This is just a temporary fix until XMLParser.getXMLString() is properly
supported
**
**
** Copyright 1999 - Interface and Control Systems, Inc.
**
*/
package com.ics.gent;


import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

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

/**
** A sample DOM writer. This sample program illustrates how to
** traverse a DOM tree in order to print a document that is parsed.
**
** This file is taken from IBM sample code DOMWriter.java from build
xml4j_2_0_15
** It is simpler than the original source code
**
** This is just a temporary fix until XMLParser.getXMLString() is properly
supported
**
** @version Revision: 10 1.6 samples/dom/DOMWriter.java, samples, xml4j2
**
** @author  IBM, Linda Derezinski
*/
public class DOMWriter
{

    private static  String PRINTWRITER_ENCODING = "UTF8"; // Encoding
    protected static StringBuffer out;                    // Holder of the
XML string(s)
    private String endline;
    /**
    ** @param inDoc XML Document containing the SML DOM tree
    **
    */
    public DOMWriter()
    {
        endline = System.getProperty("line.separator");
    } // DOMWriter()


    /**
    ** Given a node build up the XML string
    **
    ** @param  node the node create the XML
    **
    ** @return the XML string representation of node
    **
    */
    public String getXML(Node node)
    {
        out = new StringBuffer("");
        buildXML (node, 0);
        return out.toString();

    } // String getXML(Node node)

    /**
    ** create the indent string for the given indent level
    **
    ** @param  level the indent level
    **
    ** @return the indent padding
    **
    */
    private String getLevelSpacing(int level)
    {
        StringBuffer str = new StringBuffer(endline);
        for (int i = 1; i <= level; i++)
        {
            str.append ("    ");
        }
        return str.toString();
    } // String getLevelSpacing(int level)

    /**
    ** recursively build up the XML for the node
    **
    ** @param  node  the current node to process
    **         level the indent level
    **
    ** @return the type of node just processed
    **
    */
    private int buildXML (Node node, int level)
    {
        // is there anything to do?
        if ( node == null )
        {
            return 0;
        }

        boolean hasKids = true;
        int type = node.getNodeType();
        int lastType = Node.ELEMENT_NODE;
        switch ( type )
        {
        case Node.DOCUMENT_NODE:       // Process the document Element
            {
                buildXML(((Document)node).getDocumentElement(), level);
                break;
            }

        case Node.COMMENT_NODE:
            {
                out.append (getLevelSpacing (level) + "<!-- " +
node.getNodeValue() + " -->");
                break;
            }

        case Node.ELEMENT_NODE:
            {
                out.append(getLevelSpacing (level) + "<" +
node.getNodeName());
                Attr attrs[] = sortAttributes(node.getAttributes());
                for ( int i = 0; i < attrs.length; i++ )
                {
                    Attr attr = attrs[i];
                    out.append(' ' + attr.getNodeName() + "=\"" +
normalize(attr.getNodeValue()) + '"');
                }
                out.append(">");
                NodeList children = node.getChildNodes();
                int len ;
                if ( (children != null) && ((len = children.getLength())!=
0)  )
                {
                    for ( int i = 0; i < len; i++ )
                    {
                        lastType = buildXML(children.item(i), level+1);
                    }
                }
                else
                {
                    hasKids = false;
                }
                break;
            }

            // handle entity reference nodes
        case Node.ENTITY_REFERENCE_NODE:
            {
                NodeList children = node.getChildNodes();
                if ( children != null )
                {
                    int len = children.getLength();
                    for ( int i = 0; i < len; i++ )
                    {
                        buildXML(children.item(i), level+1);
                    }
                }
                break;
            }

            // print cdata sections
        case Node.CDATA_SECTION_NODE:
            {
                out.append(normalize(node.getNodeValue()));
                break;
            }

            // print text
        case Node.TEXT_NODE:


                out.append(normalize(node.getNodeValue()));
                break;
            }

            // print processing instruction
        case Node.PROCESSING_INSTRUCTION_NODE:


                out.append("<?" + node.getNodeName());
                String data = node.getNodeValue();
                if ( data != null && data.length() > 0 )
                {
                    out.append(' ' + data);
                }
                out.append("?>");
                break;
            }
        }
        // If the node just processed was an Element append the closing tag
        if ( type == Node.ELEMENT_NODE )
        {
            // Only indent if we had kids
            if (lastType != Node.TEXT_NODE && hasKids)
            {
                out.append(getLevelSpacing (level));
            }
            out.append("</" + node.getNodeName() + ">");
        }
        return type;

    } // int buildXML (Node node, int level)

    /**
    ** Returns a sorted list of attributes.
    ** NAME is in the first position
    **
    ** @param  attrs All attributes from an Element node
    **
    ** @return the sorted array of attributes with NAME in [0]
    **
    */
    protected Attr[] sortAttributes(NamedNodeMap attrs)
    {

        int len = (attrs != null) ? attrs.getLength() : 0;
        Attr array[] = new Attr[len];
        Attr nameAttr = (Attr)attrs.getNamedItem("NAME");
        int startAt;
        if (nameAttr == null)
        {
            startAt = 0;
        }
        else
        {
            startAt = 1;
            array [0] = nameAttr;
        }
        int jj = startAt;
        for ( int i = 0; i < len; i++ )
        {
            if (!(((Attr)attrs.item(i)).getName().equals("NAME")))
            {
                array[jj++] = (Attr)attrs.item(i);
            }
        }

        for ( int i = startAt; i < len - 1; i++ )
        {
            String name  = array[i].getNodeName();
            int    index = i;
            for ( int j = i + 1; j < len; j++ )
            {
                String curName = array[j].getNodeName();
                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);

    } // sortAttributes(NamedNodeMap):Attr[]

    /**
    ** Normalizes the given string.
    **
    ** @param  s String to Normalize
    **
    ** @return  Normalized string
    **
    */
    protected String normalize(String s)
    {
        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("&lt;");
                    break;
                }
            case '>':
                {
                    str.append("&gt;");
                    break;
                }
            case '&':
                {
                    str.append("&amp;");
                    break;
                }
            case '"':
                {
                    str.append("&quot;");
                    break;
                }
            case '\r':
            case '\n':

                //fall through
            default:
                {
                    str.append(ch);
                }
            }
        }

        return(str.toString());

    } //  String normalize(String s)
}


Linda Derezinski
Interface & Control Systems

 -----Original Message-----
From: 	Charlie Hart [mailto:chart@nc.rr.com]
Sent:	Friday, January 12, 2001 2:27 PM
To:	xerces-c-dev@xml.apache.org
Subject:	domprint class

I know I can modify the DOMPrint sample program to dump a DOM tree in my
program. Has anyone written a class to do this that they can send me?
thanks...charlie


---------------------------------------------------------------------
To unsubscribe, e-mail: xerces-c-dev-unsubscribe@xml.apache.org
For additional commands, e-mail: xerces-c-dev-help@xml.apache.org