Java XML Node Save writeNode(PrintWriter w, Node node, int depth)

Here you can find the source of writeNode(PrintWriter w, Node node, int depth)

Description

write Node

License

Open Source License

Declaration

private static void writeNode(PrintWriter w, Node node, int depth) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright 2011 Google Inc. All Rights Reserved.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * 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./*w  ww.ja v a 2 s.  c  o m*/
 *******************************************************************************/

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;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;

public class Main {
    public static String DEFAULT_ENCODING = "UTF-8";

    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 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 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);
    }

    /**
     * Returns a String representing the character content of the bytes; the bytes
     * must be encoded using the compiler's default encoding.
     */
    public static String toString(byte[] bytes) {
        return toString(bytes, DEFAULT_ENCODING);
    }

    /**
     * Creates a string from the bytes using the specified character set name.
     * 
     * @param bytes bytes to convert
     * @param charsetName the name of the character set to use
     * 
     * @return String for the given bytes and character set or <code>null</code>
     *         if the character set is not supported
     */
    private static String toString(byte[] bytes, String charsetName) {
        try {
            return new String(bytes, charsetName);
        } catch (UnsupportedEncodingException e) {
            // Ignored.
        }

        return null;
    }

    public static byte[] append(byte[] xs, byte x) {
        int n = xs.length;
        byte[] t = new byte[n + 1];
        System.arraycopy(xs, 0, t, 0, n);
        t[n] = x;
        return t;
    }

    @SuppressWarnings("unchecked")
    public static <T> T[] append(T[] xs, T x) {
        int n = xs.length;
        T[] t = (T[]) Array.newInstance(xs.getClass().getComponentType(), n + 1);
        System.arraycopy(xs, 0, t, 0, n);
        t[n] = x;
        return t;
    }

    @SuppressWarnings("unchecked")
    public static <T> T[] append(T[] appendToThis, T[] these) {
        if (appendToThis == null) {
            throw new NullPointerException("attempt to append to a null array");
        }

        if (these == null) {
            throw new NullPointerException("attempt to append a null array");
        }

        T[] result;
        int newSize = appendToThis.length + these.length;
        Class<?> componentType = appendToThis.getClass().getComponentType();
        result = (T[]) Array.newInstance(componentType, newSize);
        System.arraycopy(appendToThis, 0, result, 0, appendToThis.length);
        System.arraycopy(these, 0, result, appendToThis.length, these.length);
        return result;
    }
}

Related

  1. writeDOM(Node node, PrintWriter writer)
  2. writeNode(Node n, FileOutputStream o)
  3. writeNode(Node n, Writer w)
  4. writeNode(Node node, OutputStream os, boolean formatted)
  5. writeNode(Node node, OutputStream output, Map serializerParams)
  6. writeToStream(OutputStream os, Node node)
  7. writeToString(Node node)
  8. writeToString(Node node)
  9. writeXml(final Node node)