Example usage for org.w3c.dom Node DOCUMENT_NODE

List of usage examples for org.w3c.dom Node DOCUMENT_NODE

Introduction

In this page you can find the example usage for org.w3c.dom Node DOCUMENT_NODE.

Prototype

short DOCUMENT_NODE

To view the source code for org.w3c.dom Node DOCUMENT_NODE.

Click Source Link

Document

The node is a Document.

Usage

From source file:Main.java

/**
 * Generates XPath expression with the option of the Node values appended
 *
 * @param node             the Node whose XPath is to be found
 * @param parentXPath      the XPath of the parent Node
 * @param ignoreWhitespace the flag to indicate if Whitespace will be ignored
 * @param includeValues    the flag to indicate if Node values will be included
 * @param noIndex          the flag to indicate if Node indexes are included
 * @return the XPath string representation of the Node
 *//*from  www.j  av  a 2s.co  m*/

public static String generateXPath(Node node, String parentXPath, boolean ignoreWhitespace,
        boolean includeValues, boolean noIndex)

{

    boolean noValues = !includeValues;

    if (node == null)

        return "";

    Node parent = node.getParentNode();

    int index = noIndex ? 0 : getXPathNodeIndex(node, ignoreWhitespace);

    String indexStr = "";

    if (index > 0)

        indexStr = "[" + Integer.toString(index) + "]";

    if (node.getNodeType() == Node.DOCUMENT_NODE)

    {

        // return only the blank String, since all the other types are preceded with /

        return parentXPath + "";

    } else if (node.getNodeType() == Node.TEXT_NODE)

    {

        return parentXPath +

                (noValues ? "/" + node.getNodeValue() + indexStr
                        : "/TEXT(" + node.getNodeValue() + ")" + indexStr);

    } else if (node.getNodeType() == Node.ELEMENT_NODE)

    {

        return parentXPath +

                "/" + node.getNodeName() + indexStr;

    } else if (node.getNodeType() == Node.COMMENT_NODE)

    {

        return parentXPath +

                (noValues ? "/" + node.getNodeValue() + indexStr
                        : "/COMMENT(" + node.getNodeValue() + ")" + indexStr);

    } else if (node.getNodeType() == Node.ENTITY_REFERENCE_NODE)

    {

        return parentXPath +

                (noValues ? "/" + node.getNodeValue() + indexStr
                        : "/EntityReference(" + node.getNodeValue() + ")" + indexStr);

    } else if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE)

    {

        return parentXPath +

                (noValues ? "/" + node.getNodeValue() + indexStr
                        : "/PI(" + node.getNodeValue() + ")" + indexStr);

    } else if (node.getNodeType() == Node.ATTRIBUTE_NODE)

    {

        return parentXPath + "/[@" + node.getNodeName() +

                (noValues ? "" : "=" + node.getNodeValue()) + "]";

    } else if (node.getNodeType() == Node.DOCUMENT_TYPE_NODE)

    {

        return parentXPath +

                (noValues ? "/" + node.getNodeValue() : "/DOCTYPE(" + node.getNodeName() + ")");

    } else if (node.getNodeType() == Node.CDATA_SECTION_NODE)

    {

        return parentXPath +

                (noValues ? "/" + node.getNodeValue() : "/CDATA(" + node.getNodeName() + ")");

    }

    // Wont reach this far but just in case

    return "";

}

From source file:Main.java

private static void renderNode(StringBuffer sb, Node node, String margin, String indent, String lab, String rab,
        String nl) {/*from  w w w  .j a  va 2s  .  com*/
    if (node == null) {
        sb.append("null");
        return;
    }
    switch (node.getNodeType()) {

    case Node.DOCUMENT_NODE:
        //sb.append(margin + lab +"?xml version=\"1.0\" encoding=\"UTF-8\"?" + rab + nl);
        Node root = ((Document) node).getDocumentElement();
        renderNode(sb, root, margin, indent, lab, rab, nl);
        break;

    case Node.ELEMENT_NODE:
        String name = getNodeNameWithNamespace(node);
        NodeList children = node.getChildNodes();
        int nChildren = children.getLength();
        NamedNodeMap attributes = node.getAttributes();
        int nAttrs = attributes.getLength();

        boolean singleShortTextChild = (nAttrs == 0) && (nChildren == 1)
                && (children.item(0).getNodeType() == Node.TEXT_NODE)
                && (children.item(0).getTextContent().length() < 70)
                && (!children.item(0).getTextContent().contains("\n"));

        if (singleShortTextChild) {
            sb.append(margin + lab + name + ((nChildren == 0) ? "/" : "") + rab);
        } else if (nAttrs == 0 && !singleShortTextChild) {
            sb.append(margin + lab + name + ((nChildren == 0) ? "/" : "") + rab + nl);
        } else if (nAttrs == 1) {
            Node attr = attributes.item(0);
            String attrName = getNodeNameWithNamespace(attr);
            sb.append(margin + lab + name + " " + attrName + "=\"" + escapeChars(attr.getNodeValue()) + "\""
                    + ((nChildren == 0) ? "/" : "") + rab + nl);
        } else {
            sb.append(margin + lab + name + nl);
            for (int i = 0; i < nAttrs; i++) {
                Node attr = attributes.item(i);
                String attrName = getNodeNameWithNamespace(attr);
                sb.append(margin + indent + attrName + "=\"" + escapeChars(attr.getNodeValue()));
                if (i < nAttrs - 1)
                    sb.append("\"" + nl);
                else
                    sb.append("\"" + ((nChildren == 0) ? "/" : "") + rab + nl);
            }
        }
        if (singleShortTextChild) {
            String text = escapeChars(node.getTextContent());
            sb.append(text.trim());
            sb.append(lab + "/" + name + rab + nl);
        } else {
            for (int i = 0; i < nChildren; i++) {
                renderNode(sb, children.item(i), margin + indent, indent, lab, rab, nl);
            }
        }
        if (nChildren != 0 && !singleShortTextChild)
            sb.append(margin + lab + "/" + name + rab + nl);
        break;

    case Node.TEXT_NODE:
        String text = escapeChars(node.getNodeValue());
        String[] lines = text.split("\n");
        for (String line : lines) {
            line = line.trim();
            if (!line.equals(""))
                sb.append(margin + line + nl);
        }
        break;

    case Node.CDATA_SECTION_NODE:
        String cdataText = node.getNodeValue();
        String[] cdataLines = cdataText.split("\n");
        sb.append(margin + lab + "![CDATA[" + nl);
        for (String line : cdataLines) {
            line = line.trim();
            if (!line.equals(""))
                sb.append(margin + indent + line + nl);
        }
        sb.append(margin + "]]" + rab + nl);
        break;

    case Node.PROCESSING_INSTRUCTION_NODE:
        sb.append(margin + lab + "?" + node.getNodeName() + " " + escapeChars(node.getNodeValue()) + "?" + rab
                + nl);
        break;

    case Node.ENTITY_REFERENCE_NODE:
        sb.append("&" + node.getNodeName() + ";");
        break;

    case Node.DOCUMENT_TYPE_NODE:
        // Ignore document type nodes
        break;

    case Node.COMMENT_NODE:
        sb.append(margin + lab + "!--" + node.getNodeValue() + "--" + rab + nl);
        break;
    }
    return;
}

From source file:DOMTreeFull.java

public static String toString(Node node) {
    StringBuffer sb = new StringBuffer();

    // is there anything to do?
    if (node == null) {
        return "";
    }//from   w  ww  . ja  va 2 s .  co  m

    int type = node.getNodeType();
    sb.append(whatArray[type]);
    sb.append(" : ");
    sb.append(node.getNodeName());
    String value = node.getNodeValue();
    if (value != null) {
        sb.append(" Value: \"");
        sb.append(value);
        sb.append("\"");
    }

    switch (type) {

    // document
    case Node.DOCUMENT_NODE: {
        break;
    }

    // element with attributes
    case Node.ELEMENT_NODE: {
        Attr attrs[] = sortAttributes(node.getAttributes());
        if (attrs.length > 0)
            sb.append(" ATTRS:");
        for (int i = 0; i < attrs.length; i++) {
            Attr attr = attrs[i];

            sb.append(' ');
            sb.append(attr.getNodeName());
            sb.append("=\"");
            sb.append(normalize(attr.getNodeValue()));
            sb.append('"');
        }
        sb.append('>');
        break;
    }

    // handle entity reference nodes
    case Node.ENTITY_REFERENCE_NODE: {
        break;
    }

    // cdata sections
    case Node.CDATA_SECTION_NODE: {
        break;
    }

    // text
    case Node.TEXT_NODE: {
        break;
    }

    // processing instruction
    case Node.PROCESSING_INSTRUCTION_NODE: {
        break;
    }

    // comment node
    case Node.COMMENT_NODE: {
        break;
    }
    // DOCTYPE node
    case Node.DOCUMENT_TYPE_NODE: {
        break;
    }
    // Notation node
    case Node.NOTATION_NODE: {
        sb.append("public:");
        String id = ((Notation) node).getPublicId();
        if (id == null) {
            sb.append("PUBLIC ");
            sb.append(id);
            sb.append(" ");
        }
        id = ((Notation) node).getSystemId();
        if (id == null) {
            sb.append("system: ");
            sb.append(id);
            sb.append(" ");
        }
        break;
    }
    }
    return sb.toString();
}

From source file:DOM2SAX.java

/**
 * Writes a node using the given writer.
 * @param node node to serialize//from www.j a v a  2s  . c om
 * @throws SAXException In case of a problem while writing XML
 */
private void writeNode(Node node) throws SAXException {
    if (node == null) {
        return;
    }

    switch (node.getNodeType()) {
    case Node.ATTRIBUTE_NODE: // handled by ELEMENT_NODE
    case Node.DOCUMENT_FRAGMENT_NODE:
    case Node.DOCUMENT_TYPE_NODE:
    case Node.ENTITY_NODE:
    case Node.ENTITY_REFERENCE_NODE:
    case Node.NOTATION_NODE:
        // These node types are ignored!!!
        break;
    case Node.CDATA_SECTION_NODE:
        final String cdata = node.getNodeValue();
        if (lexicalHandler != null) {
            lexicalHandler.startCDATA();
            contentHandler.characters(cdata.toCharArray(), 0, cdata.length());
            lexicalHandler.endCDATA();
        } else {
            // in the case where there is no lex handler, we still
            // want the text of the cdate to make its way through.
            contentHandler.characters(cdata.toCharArray(), 0, cdata.length());
        }
        break;

    case Node.COMMENT_NODE: // should be handled!!!
        if (lexicalHandler != null) {
            final String value = node.getNodeValue();
            lexicalHandler.comment(value.toCharArray(), 0, value.length());
        }
        break;
    case Node.DOCUMENT_NODE:
        contentHandler.startDocument();
        Node next = node.getFirstChild();
        while (next != null) {
            writeNode(next);
            next = next.getNextSibling();
        }
        contentHandler.endDocument();
        break;

    case Node.ELEMENT_NODE:
        String prefix;
        List pushedPrefixes = new java.util.ArrayList();
        final AttributesImpl attrs = new AttributesImpl();
        final NamedNodeMap map = node.getAttributes();
        final int length = map.getLength();

        // Process all namespace declarations
        for (int i = 0; i < length; i++) {
            final Node attr = map.item(i);
            final String qnameAttr = attr.getNodeName();

            // Ignore everything but NS declarations here
            if (qnameAttr.startsWith(XMLNS_PREFIX)) {
                final String uriAttr = attr.getNodeValue();
                final int colon = qnameAttr.lastIndexOf(':');
                prefix = (colon > 0) ? qnameAttr.substring(colon + 1) : EMPTYSTRING;
                if (startPrefixMapping(prefix, uriAttr)) {
                    pushedPrefixes.add(prefix);
                }
            }
        }

        // Process all other attributes
        for (int i = 0; i < length; i++) {
            final Node attr = map.item(i);
            final String qnameAttr = attr.getNodeName();

            // Ignore NS declarations here
            if (!qnameAttr.startsWith(XMLNS_PREFIX)) {
                final String uriAttr = attr.getNamespaceURI();

                // Uri may be implicitly declared
                if (uriAttr != null) {
                    final int colon = qnameAttr.lastIndexOf(':');
                    prefix = (colon > 0) ? qnameAttr.substring(0, colon) : EMPTYSTRING;
                    if (startPrefixMapping(prefix, uriAttr)) {
                        pushedPrefixes.add(prefix);
                    }
                }

                // Add attribute to list
                attrs.addAttribute(attr.getNamespaceURI(), getLocalName(attr), qnameAttr, "CDATA",
                        attr.getNodeValue());
            }
        }

        // Now process the element itself
        final String qname = node.getNodeName();
        final String uri = node.getNamespaceURI();
        final String localName = getLocalName(node);

        // Uri may be implicitly declared
        if (uri != null) {
            final int colon = qname.lastIndexOf(':');
            prefix = (colon > 0) ? qname.substring(0, colon) : EMPTYSTRING;
            if (startPrefixMapping(prefix, uri)) {
                pushedPrefixes.add(prefix);
            }
        }

        // Generate SAX event to start element
        contentHandler.startElement(uri, localName, qname, attrs);

        // Traverse all child nodes of the element (if any)
        next = node.getFirstChild();
        while (next != null) {
            writeNode(next);
            next = next.getNextSibling();
        }

        // Generate SAX event to close element
        contentHandler.endElement(uri, localName, qname);

        // Generate endPrefixMapping() for all pushed prefixes
        final int nPushedPrefixes = pushedPrefixes.size();
        for (int i = 0; i < nPushedPrefixes; i++) {
            endPrefixMapping((String) pushedPrefixes.get(i));
        }
        break;

    case Node.PROCESSING_INSTRUCTION_NODE:
        contentHandler.processingInstruction(node.getNodeName(), node.getNodeValue());
        break;

    case Node.TEXT_NODE:
        final String data = node.getNodeValue();
        contentHandler.characters(data.toCharArray(), 0, data.length());
        break;
    default:
        //nop
    }
}

From source file:net.sf.jasperreports.engine.util.JRXmlUtils.java

/**
 * Creates a document having a node as root.
 * //from  w  w  w  . j  a  v a  2s . c om
 * @param sourceNode the node
 * @return a document having the specified node as root
 * @throws JRException
 */
public static Document createDocument(Node sourceNode, boolean isNamespaceAware) throws JRException {
    Document doc = JRXmlUtils.createDocumentBuilder(isNamespaceAware).newDocument();
    Node source;
    if (sourceNode.getNodeType() == Node.DOCUMENT_NODE) {
        source = ((Document) sourceNode).getDocumentElement();
    } else {
        source = sourceNode;
    }

    Node node = doc.importNode(source, true);
    doc.appendChild(node);

    return doc;
}

From source file:Counter.java

/** Traverses the specified node, recursively. */
public void count(Node node) {

    // is there anything to do?
    if (node == null) {
        return;/*from w  ww  .j av a2  s.  co m*/
    }

    int type = node.getNodeType();
    switch (type) {
    case Node.DOCUMENT_NODE: {
        fElements = 0;
        fAttributes = 0;
        fCharacters = 0;
        fIgnorableWhitespace = 0;
        Document document = (Document) node;
        count(document.getDocumentElement());
        break;
    }

    case Node.ELEMENT_NODE: {
        fElements++;
        NamedNodeMap attrs = node.getAttributes();
        if (attrs != null) {
            fAttributes += attrs.getLength();
        }
        // drop through to entity reference
    }

    case Node.ENTITY_REFERENCE_NODE: {
        Node child = node.getFirstChild();
        while (child != null) {
            count(child);
            child = child.getNextSibling();
        }
        break;
    }

    case Node.CDATA_SECTION_NODE: {
        fCharacters += ((Text) node).getLength();
        break;
    }

    case Node.TEXT_NODE: {
        if (fDocumentInfo != null) {
            Text text = (Text) node;
            int length = text.getLength();
            if (fDocumentInfo.isIgnorableWhitespace(text)) {
                fIgnorableWhitespace += length;
            } else {
                fCharacters += length;
            }
        }
        break;
    }
    }

}

From source file:de.betterform.xml.dom.DOMUtil.java

/**
 * returns the first child of the contextnode which has the specified tagname regardless of the depth in the tree.
 *
 * @param contextNode where to start the search
 * @param tag         the name of the wanted child
 * @return the first child found under the contextnode
 *//*from  www .  j  ava2  s.c om*/
public static Node getFirstChildByTagName(Node contextNode, String tag) {
    Node n = null;

    if (contextNode.getNodeType() == Node.DOCUMENT_NODE) {
        n = ((Document) contextNode).getDocumentElement();

        if (!n.getNodeName().equals(tag)) {
            n = null;
        }
    } else {
        NodeList nodes = ((Element) contextNode).getElementsByTagName(tag);

        if (nodes != null) {
            n = nodes.item(0);
        }
    }

    return n;
}

From source file:DOMWriter.java

private void printInternal(Node node, boolean indentEndMarker) {
    // is there anything to do?
    if (node == null) {
        return;//w  w  w  .  ja  v a 2  s. c o  m
    }

    // JBAS-2117 - Don't skip the DOCUMENT_NODE
    // if (node instanceof Document) node = ((Document)node).getDocumentElement();

    if (wroteXMLDeclaration == false && writeXMLDeclaration == true && canonical == false) {
        out.print("<?xml version='1.0'");
        if (charsetName != null)
            out.print(" encoding='" + charsetName + "'");

        out.print("?>");
        if (prettyprint)
            out.println();

        wroteXMLDeclaration = true;
    }

    int type = node.getNodeType();
    boolean hasChildNodes = node.getChildNodes().getLength() > 0;

    String nodeName = node.getNodeName();
    switch (type) {
    // print document
    case Node.DOCUMENT_NODE: {
        NodeList children = node.getChildNodes();
        for (int iChild = 0; iChild < children.getLength(); iChild++) {
            printInternal(children.item(iChild), false);
        }
        out.flush();
        break;
    }

    // print element with attributes
    case Node.ELEMENT_NODE: {
        Element element = (Element) node;
        if (prettyprint) {
            for (int i = 0; i < prettyIndent; i++) {
                out.print(' ');
            }
            prettyIndent++;
        }

        out.print('<');
        out.print(nodeName);

        Map nsMap = new HashMap();
        String elPrefix = node.getPrefix();
        String elNamespaceURI = node.getNamespaceURI();
        if (elPrefix != null) {
            String nsURI = getNamespaceURI(elPrefix, element, rootNode);
            nsMap.put(elPrefix, nsURI);
        }

        Attr attrs[] = sortAttributes(node.getAttributes());
        for (int i = 0; i < attrs.length; i++) {
            Attr attr = attrs[i];
            String atPrefix = attr.getPrefix();
            String atName = attr.getNodeName();
            String atValue = normalize(attr.getNodeValue(), canonical);

            if (atName.equals("xmlns"))
                currentDefaultNamespace = atValue;

            if (atPrefix != null && !atPrefix.equals("xmlns") && !atPrefix.equals("xml")) {
                String nsURI = getNamespaceURI(atPrefix, element, rootNode);
                nsMap.put(atPrefix, nsURI);
                // xsi:type='ns1:SubType', xsi:type='xsd:string'
                if (atName.equals(atPrefix + ":type") && atValue.indexOf(":") > 0) {
                    // xsi defined on the envelope
                    if (nsURI == null)
                        nsURI = getNamespaceURI(atPrefix, element, null);

                    if ("http://www.w3.org/2001/XMLSchema-instance".equals(nsURI)) {
                        String typePrefix = atValue.substring(0, atValue.indexOf(":"));
                        String typeURI = getNamespaceURI(typePrefix, element, rootNode);
                        nsMap.put(typePrefix, typeURI);
                    }
                }
            }

            out.print(" " + atName + "='" + atValue + "'");
        }

        // Add namespace declaration for prefixes
        // that are defined further up the tree
        if (completeNamespaces) {
            Iterator itPrefix = nsMap.keySet().iterator();
            while (itPrefix.hasNext()) {
                String prefix = (String) itPrefix.next();
                String nsURI = (String) nsMap.get(prefix);
                if (nsURI == null) {
                    nsURI = getNamespaceURI(prefix, element, null);
                    out.print(" xmlns:" + prefix + "='" + nsURI + "'");
                }
            }
        }

        // The SAX ContentHandler will by default not add the namespace declaration
        // <Hello xmlns='http://somens'>World</Hello>
        if (elPrefix == null && elNamespaceURI != null) {
            String defaultNamespace = element.getAttribute("xmlns");
            if (defaultNamespace.length() == 0 && !elNamespaceURI.equals(currentDefaultNamespace)) {
                out.print(" xmlns='" + elNamespaceURI + "'");
                currentDefaultNamespace = elNamespaceURI;
            }
        }

        if (hasChildNodes) {
            out.print('>');
        }

        // Find out if the end marker is indented
        indentEndMarker = isEndMarkerIndented(node);

        if (indentEndMarker) {
            out.print('\n');
        }

        NodeList childNodes = node.getChildNodes();
        int len = childNodes.getLength();
        for (int i = 0; i < len; i++) {
            Node childNode = childNodes.item(i);
            printInternal(childNode, false);
        }
        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++) {
                    printInternal(children.item(i), false);
                }
            }
        } else {
            out.print('&');
            out.print(nodeName);
            out.print(';');
        }
        break;
    }

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

    // print text
    case Node.TEXT_NODE: {
        String text = normalize(node.getNodeValue(), canonical);
        if (text.trim().length() > 0) {
            out.print(text);
        } else if (prettyprint == false && ignoreWhitespace == false) {
            out.print(text);
        }
        break;
    }

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

    // print comment
    case Node.COMMENT_NODE: {
        for (int i = 0; i < prettyIndent; i++) {
            out.print(' ');
        }

        out.print("<!--");
        String data = node.getNodeValue();
        if (data != null) {
            out.print(data);
        }
        out.print("-->");

        if (prettyprint) {
            out.print('\n');
        }

        break;
    }
    }

    if (type == Node.ELEMENT_NODE) {
        if (prettyprint)
            prettyIndent--;

        if (hasChildNodes == false) {
            out.print("/>");
        } else {
            if (indentEndMarker) {
                for (int i = 0; i < prettyIndent; i++) {
                    out.print(' ');
                }
            }

            out.print("</");
            out.print(nodeName);
            out.print('>');
        }

        if (prettyIndent > 0) {
            out.print('\n');
        }
    }
    out.flush();
}

From source file:DOMWriter.java

private void printInternal(Node node, boolean indentEndMarker) {
    // is there anything to do?
    if (node == null) {
        return;//  w ww  .j a  v  a2s. c  o m
    }

    // JBAS-2117 - Don't skip the DOCUMENT_NODE
    // if (node instanceof Document) node =
    // ((Document)node).getDocumentElement();

    if (wroteXMLDeclaration == false && writeXMLDeclaration == true && canonical == false) {
        out.print("<?xml version='1.0'");
        if (charsetName != null)
            out.print(" encoding='" + charsetName + "'");

        out.print("?>");
        if (prettyprint)
            out.println();

        wroteXMLDeclaration = true;
    }

    int type = node.getNodeType();
    boolean hasChildNodes = node.getChildNodes().getLength() > 0;

    String nodeName = node.getNodeName();
    switch (type) {
    // print document
    case Node.DOCUMENT_NODE: {
        NodeList children = node.getChildNodes();
        for (int iChild = 0; iChild < children.getLength(); iChild++) {
            printInternal(children.item(iChild), false);
        }
        out.flush();
        break;
    }

    // print element with attributes
    case Node.ELEMENT_NODE: {
        Element element = (Element) node;
        if (prettyprint) {
            for (int i = 0; i < prettyIndent; i++) {
                out.print(' ');
            }
            prettyIndent++;
        }

        out.print('<');
        out.print(nodeName);

        Map nsMap = new HashMap();
        String elPrefix = node.getPrefix();
        String elNamespaceURI = node.getNamespaceURI();
        if (elPrefix != null) {
            String nsURI = getNamespaceURI(elPrefix, element, rootNode);
            nsMap.put(elPrefix, nsURI);
        }

        Attr attrs[] = sortAttributes(node.getAttributes());
        for (int i = 0; i < attrs.length; i++) {
            Attr attr = attrs[i];
            String atPrefix = attr.getPrefix();
            String atName = attr.getNodeName();
            String atValue = normalize(attr.getNodeValue(), canonical);

            if (atName.equals("xmlns"))
                currentDefaultNamespace = atValue;

            if (atPrefix != null && !atPrefix.equals("xmlns") && !atPrefix.equals("xml")) {
                String nsURI = getNamespaceURI(atPrefix, element, rootNode);
                nsMap.put(atPrefix, nsURI);
                // xsi:type='ns1:SubType', xsi:type='xsd:string'
                if (atName.equals(atPrefix + ":type") && atValue.indexOf(":") > 0) {
                    // xsi defined on the envelope
                    if (nsURI == null)
                        nsURI = getNamespaceURI(atPrefix, element, null);

                    if ("http://www.w3.org/2001/XMLSchema-instance".equals(nsURI)) {
                        String typePrefix = atValue.substring(0, atValue.indexOf(":"));
                        String typeURI = getNamespaceURI(typePrefix, element, rootNode);
                        nsMap.put(typePrefix, typeURI);
                    }
                }
            }

            out.print(" " + atName + "='" + atValue + "'");
        }

        // Add namespace declaration for prefixes
        // that are defined further up the tree
        if (completeNamespaces) {
            Iterator itPrefix = nsMap.keySet().iterator();
            while (itPrefix.hasNext()) {
                String prefix = (String) itPrefix.next();
                String nsURI = (String) nsMap.get(prefix);
                if (nsURI == null) {
                    nsURI = getNamespaceURI(prefix, element, null);
                    out.print(" xmlns:" + prefix + "='" + nsURI + "'");
                }
            }
        }

        // The SAX ContentHandler will by default not add the namespace
        // declaration
        // <Hello xmlns='http://somens'>World</Hello>
        if (elPrefix == null && elNamespaceURI != null) {
            String defaultNamespace = element.getAttribute("xmlns");
            if (defaultNamespace.length() == 0 && !elNamespaceURI.equals(currentDefaultNamespace)) {
                out.print(" xmlns='" + elNamespaceURI + "'");
                currentDefaultNamespace = elNamespaceURI;
            }
        }

        if (hasChildNodes) {
            out.print('>');
        }

        // Find out if the end marker is indented
        indentEndMarker = isEndMarkerIndented(node);

        if (indentEndMarker) {
            out.print('\n');
        }

        NodeList childNodes = node.getChildNodes();
        int len = childNodes.getLength();
        for (int i = 0; i < len; i++) {
            Node childNode = childNodes.item(i);
            printInternal(childNode, false);
        }
        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++) {
                    printInternal(children.item(i), false);
                }
            }
        } else {
            out.print('&');
            out.print(nodeName);
            out.print(';');
        }
        break;
    }

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

    // print text
    case Node.TEXT_NODE: {
        String text = normalize(node.getNodeValue(), canonical);
        if (text.trim().length() > 0) {
            out.print(text);
        } else if (prettyprint == false && ignoreWhitespace == false) {
            out.print(text);
        }
        break;
    }

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

    // print comment
    case Node.COMMENT_NODE: {
        for (int i = 0; i < prettyIndent; i++) {
            out.print(' ');
        }

        out.print("<!--");
        String data = node.getNodeValue();
        if (data != null) {
            out.print(data);
        }
        out.print("-->");

        if (prettyprint) {
            out.print('\n');
        }

        break;
    }
    }

    if (type == Node.ELEMENT_NODE) {
        if (prettyprint)
            prettyIndent--;

        if (hasChildNodes == false) {
            out.print("/>");
        } else {
            if (indentEndMarker) {
                for (int i = 0; i < prettyIndent; i++) {
                    out.print(' ');
                }
            }

            out.print("</");
            out.print(nodeName);
            out.print('>');
        }

        if (prettyIndent > 0) {
            out.print('\n');
        }
    }
    out.flush();
}

From source file:DOMWriter.java

/** Writes the specified node, recursively. */
public void write(Node node) {

    // is there anything to do?
    if (node == null) {
        return;/*from ww  w. j  av a 2  s  . com*/
    }

    short type = node.getNodeType();
    switch (type) {
    case Node.DOCUMENT_NODE: {
        Document document = (Document) node;
        fXML11 = "1.1".equals(getVersion(document));
        if (!fCanonical) {
            if (fXML11) {
                fOut.println("<?xml version=\"1.1\" encoding=\"UTF-8\"?>");
            } else {
                fOut.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            }
            fOut.flush();
            write(document.getDoctype());
        }
        write(document.getDocumentElement());
        break;
    }

    case Node.DOCUMENT_TYPE_NODE: {
        DocumentType doctype = (DocumentType) node;
        fOut.print("<!DOCTYPE ");
        fOut.print(doctype.getName());
        String publicId = doctype.getPublicId();
        String systemId = doctype.getSystemId();
        if (publicId != null) {
            fOut.print(" PUBLIC '");
            fOut.print(publicId);
            fOut.print("' '");
            fOut.print(systemId);
            fOut.print('\'');
        } else if (systemId != null) {
            fOut.print(" SYSTEM '");
            fOut.print(systemId);
            fOut.print('\'');
        }
        String internalSubset = doctype.getInternalSubset();
        if (internalSubset != null) {
            fOut.println(" [");
            fOut.print(internalSubset);
            fOut.print(']');
        }
        fOut.println('>');
        break;
    }

    case Node.ELEMENT_NODE: {
        fOut.print('<');
        fOut.print(node.getNodeName());
        Attr attrs[] = sortAttributes(node.getAttributes());
        for (int i = 0; i < attrs.length; i++) {
            Attr attr = attrs[i];
            fOut.print(' ');
            fOut.print(attr.getNodeName());
            fOut.print("=\"");
            normalizeAndPrint(attr.getNodeValue(), true);
            fOut.print('"');
        }
        fOut.print('>');
        fOut.flush();

        Node child = node.getFirstChild();
        while (child != null) {
            write(child);
            child = child.getNextSibling();
        }
        break;
    }

    case Node.ENTITY_REFERENCE_NODE: {
        if (fCanonical) {
            Node child = node.getFirstChild();
            while (child != null) {
                write(child);
                child = child.getNextSibling();
            }
        } else {
            fOut.print('&');
            fOut.print(node.getNodeName());
            fOut.print(';');
            fOut.flush();
        }
        break;
    }

    case Node.CDATA_SECTION_NODE: {
        if (fCanonical) {
            normalizeAndPrint(node.getNodeValue(), false);
        } else {
            fOut.print("<![CDATA[");
            fOut.print(node.getNodeValue());
            fOut.print("]]&gt;");
        }
        fOut.flush();
        break;
    }

    case Node.TEXT_NODE: {
        normalizeAndPrint(node.getNodeValue(), false);
        fOut.flush();
        break;
    }

    case Node.PROCESSING_INSTRUCTION_NODE: {
        fOut.print("<?");
        fOut.print(node.getNodeName());
        String data = node.getNodeValue();
        if (data != null && data.length() > 0) {
            fOut.print(' ');
            fOut.print(data);
        }
        fOut.print("?>");
        fOut.flush();
        break;
    }

    case Node.COMMENT_NODE: {
        if (!fCanonical) {
            fOut.print("<!--");
            String comment = node.getNodeValue();
            if (comment != null && comment.length() > 0) {
                fOut.print(comment);
            }
            fOut.print("-->");
            fOut.flush();
        }
    }
    }

    if (type == Node.ELEMENT_NODE) {
        fOut.print("</");
        fOut.print(node.getNodeName());
        fOut.print('>');
        fOut.flush();
    }

}