Java XML Document to Writer writeDocument(PrintWriter w, Document d)

Here you can find the source of writeDocument(PrintWriter w, Document d)

Description

write Document

License

Apache License

Declaration

private static void writeDocument(PrintWriter w, Document d) throws IOException 

Method Source Code


//package com.java2s;
/*/* w  w w  . jav  a2s  . c  om*/
 * Copyright 2008 Google Inc.
 *
 * 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.
 */

import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.Text;

import java.io.IOException;

import java.io.PrintWriter;

public class Main {
    private static void writeDocument(PrintWriter w, Document d) throws IOException {
        w.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        Node c = d.getFirstChild();
        while (c != null) {
            writeNode(w, c, 0);
            c = c.getNextSibling();
        }
    }

    private static void writeNode(PrintWriter w, Node node, int depth) throws IOException {
        short nodeType = node.getNodeType();
        switch (nodeType) {
        case Node.ELEMENT_NODE:
            writeElement(w, (Element) node, depth);
            break;
        case Node.ATTRIBUTE_NODE:
            writeAttribute(w, (Attr) node, depth);
            break;
        case Node.DOCUMENT_NODE:
            writeDocument(w, (Document) node);
            break;
        case Node.TEXT_NODE:
            writeText(w, (Text) node);
            break;

        case Node.COMMENT_NODE:
        case Node.CDATA_SECTION_NODE:
        case Node.ENTITY_REFERENCE_NODE:
        case Node.ENTITY_NODE:
        case Node.PROCESSING_INSTRUCTION_NODE:
        default:
            throw new RuntimeException("Unsupported DOM node type: " + nodeType);
        }
    }

    private static void writeElement(PrintWriter w, Element el, int depth) throws IOException {
        String tagName = el.getTagName();

        writeIndent(w, depth);
        w.write('<');
        w.write(tagName);
        NamedNodeMap attrs = el.getAttributes();
        for (int i = 0, n = attrs.getLength(); i < n; ++i) {
            w.write(' ');
            writeNode(w, attrs.item(i), depth);
        }

        Node c = el.getFirstChild();
        if (c != null) {
            // There is at least one child.
            //
            w.println('>');

            // Write the children.
            //
            while (c != null) {
                writeNode(w, c, depth + 1);
                w.println();
                c = c.getNextSibling();
            }

            // Write the closing tag.
            //
            writeIndent(w, depth);
            w.write("</");
            w.write(tagName);
            w.print('>');
        } else {
            // There are no children, so just write the short form close.
            //
            w.print("/>");
        }
    }

    private static void writeAttribute(PrintWriter w, Attr attr, int depth) throws IOException {
        w.write(attr.getName());
        w.write('=');
        Node c = attr.getFirstChild();
        while (c != null) {
            w.write('"');
            writeNode(w, c, depth);
            w.write('"');
            c = c.getNextSibling();
        }
    }

    private static void writeText(PrintWriter w, Text text) throws DOMException {
        String nodeValue = text.getNodeValue();
        String escaped = escapeXml(nodeValue);
        w.write(escaped);
    }

    private static void writeIndent(PrintWriter w, int depth) {
        for (int i = 0; i < depth; ++i) {
            w.write('\t');
        }
    }

    /**
     * Escapes '&', '<', '>', '"', and '\'' to their XML entity equivalents.
     */
    public static String escapeXml(String unescaped) {
        StringBuilder builder = new StringBuilder();
        escapeXml(unescaped, 0, unescaped.length(), true, builder);
        return builder.toString();
    }

    /**
     * Escapes '&', '<', '>', '"', and optionally ''' to their XML entity
     * equivalents. The portion of the input string between start (inclusive) and
     * end (exclusive) is scanned.  The output is appended to the given
     * StringBuilder.
     *
     * @param code the input String
     * @param start the first character position to scan.
     * @param end the character position following the last character to scan.
     * @param quoteApostrophe if true, the &apos; character is quoted as
     *     &amp;apos;
     * @param builder a StringBuilder to be appended with the output.
     */
    public static void escapeXml(String code, int start, int end, boolean quoteApostrophe, StringBuilder builder) {
        int lastIndex = 0;
        int len = end - start;
        char[] c = new char[len];

        code.getChars(start, end, c, 0);
        for (int i = 0; i < len; i++) {
            switch (c[i]) {
            case '&':
                builder.append(c, lastIndex, i - lastIndex);
                builder.append("&amp;");
                lastIndex = i + 1;
                break;
            case '>':
                builder.append(c, lastIndex, i - lastIndex);
                builder.append("&gt;");
                lastIndex = i + 1;
                break;
            case '<':
                builder.append(c, lastIndex, i - lastIndex);
                builder.append("&lt;");
                lastIndex = i + 1;
                break;
            case '\"':
                builder.append(c, lastIndex, i - lastIndex);
                builder.append("&quot;");
                lastIndex = i + 1;
                break;
            case '\'':
                if (quoteApostrophe) {
                    builder.append(c, lastIndex, i - lastIndex);
                    builder.append("&apos;");
                    lastIndex = i + 1;
                }
                break;
            default:
                break;
            }
        }
        builder.append(c, lastIndex, len - lastIndex);
    }
}

Related

  1. toXML(Document doc, Writer w, boolean indent)
  2. write(Writer out, Document doc)
  3. writeDocument(Document doc, Writer out)
  4. writeDocument(Document doc, Writer w)
  5. writeDocument(Document document, Writer writer, Integer indent)
  6. writeDom(Document doc, Writer w)
  7. writeOutDOM(Document doc, Writer writer)
  8. writeXML(final Document doc, final Writer writer)