Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import org.w3c.dom.*;

public class Main {
    /** Helper method - Converts an XML <I>Element</I> to a <I>String</I> object, but
    excludes the top level (wrapper) Element from the returned <I>String</I>.
       @param pElement An <I>org.w3c.dom.Element</I> object who's children are
      to be serialized to a <I>String</I>.
       @return <I>String</I> representation of the <I>Element</I>'s children.
     */
    public static String convertElementChildrenToString(Element pElement) {
        String strReturn = "";
        NodeList pChildren = pElement.getChildNodes();
        int nCount = pChildren.getLength();

        for (int i = 0; i < nCount; i++) {
            Node pChild = pChildren.item(i);

            if (pChild instanceof Element)
                strReturn += convertElementToString((Element) pChild);
        }

        return strReturn;
    }

    /** Helper method - Converts an XML <I>Element</I> to a <I>String</I> object.
       @param pElement An <I>org.w3c.dom.Element</I> object to be serialized to a <I>String</I>.
       @return <I>String</I> representation of the <I>Element</I>.
     */
    public static String convertElementToString(Element pElement) {
        // Local variables.
        int nCount = 0;

        // Start the element.
        String strName = pElement.getNodeName();
        String strReturn = "<" + strName;

        // Get the list of attributes.
        NamedNodeMap pNodeMap = pElement.getAttributes();
        nCount = pNodeMap.getLength();

        // Build the attributes.
        for (int i = 0; i < nCount; i++) {
            Attr pAttr = (Attr) pNodeMap.item(i);
            strReturn += " " + pAttr.getNodeName() + "=\"" + pAttr.getNodeValue() + "\"";
        }

        // Get the list of children.
        NodeList pChildren = pElement.getChildNodes();
        nCount = pChildren.getLength();

        // If no children exist, return a single node.
        if (0 == nCount)
            return strReturn + " />";

        // Close node.
        strReturn += ">";

        // Build out the children nodes.
        for (int i = 0; i < nCount; i++) {
            Node pChild = pChildren.item(i);

            if (pChild instanceof CharacterData)
                strReturn += ((CharacterData) pChild).getData();
            else if (pChild instanceof Element)
                strReturn += convertElementToString((Element) pChild);
        }

        return strReturn + "</" + strName + ">";
    }
}