Example usage for org.w3c.dom Node getNodeValue

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

Introduction

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

Prototype

public String getNodeValue() throws DOMException;

Source Link

Document

The value of this node, depending on its type; see the table above.

Usage

From source file:Main.java

/**
 * Serialise the supplied W3C DOM subtree.
 *
 * @param nodeList The DOM subtree as a NodeList.
 * @param format Format the output.//w  w  w .  j  a  v  a 2  s  .  c  om
 * @param writer The target writer for serialization.
 * @throws DOMException Unable to serialise the DOM.
 */
public static void serialize(NodeList nodeList, boolean format, Writer writer) throws DOMException {

    if (nodeList == null) {
        throw new IllegalArgumentException("null 'subtree' NodeIterator arg in method call.");
    }

    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer;

        if (format) {
            try {
                factory.setAttribute("indent-number", new Integer(4));
            } catch (Exception e) {
                // Ignore... Xalan may throw on this!!
                // We handle Xalan indentation below (yeuckkk) ...
            }
        }
        transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        if (format) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "4");
        }

        int listLength = nodeList.getLength();

        // Iterate through the Node List.
        for (int i = 0; i < listLength; i++) {
            Node node = nodeList.item(i);

            if (isTextNode(node)) {
                writer.write(node.getNodeValue());
            } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
                writer.write(((Attr) node).getValue());
            } else if (node.getNodeType() == Node.ELEMENT_NODE) {
                transformer.transform(new DOMSource(node), new StreamResult(writer));
            }
        }
    } catch (Exception e) {
        DOMException domExcep = new DOMException(DOMException.INVALID_ACCESS_ERR,
                "Unable to serailise DOM subtree.");
        domExcep.initCause(e);
        throw domExcep;
    }
}

From source file:Main.java

/**
 * Used for debuging//from w  w  w .j av  a 2s .co m
 * 
 * @param parent
 *            Element
 * @param out
 *            PrintStream
 * @param deep
 *            boolean
 * @param prefix
 *            String
 */
public static void printChildElements(Element parent, PrintStream out, boolean deep, String prefix) {
    out.print(prefix + "<" + parent.getNodeName());
    NamedNodeMap attrs = parent.getAttributes();
    Node node;
    for (int i = 0; i < attrs.getLength(); i++) {
        node = attrs.item(i);
        out.print(" " + node.getNodeName() + "=\"" + node.getNodeValue() + "\"");
    }
    out.println(">");

    // String data = getElementTextValueDeprecated(parent);
    String data = parent.getNodeValue();
    if (data != null && data.trim().length() > 0) {
        out.println(prefix + "\t" + data);
    }

    data = getElementCDataValue(parent);
    if (data != null && data.trim().length() > 0) {
        out.println(prefix + "\t<![CDATA[" + data + "]]>");
    }

    NodeList nodes = parent.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (deep) {
                printChildElements((Element) node, out, deep, prefix + "\t");
            } else {
                out.println(prefix + node.getNodeName());
            }
        }
    }

    out.println(prefix + "</" + parent.getNodeName() + ">");
}

From source file:Main.java

public static Object getContent(Element element) {
    NodeList nl = element.getChildNodes();
    StringBuilder content = new StringBuilder();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        switch (node.getNodeType()) {
        case Node.ELEMENT_NODE:
            return node;
        case Node.CDATA_SECTION_NODE:
        case Node.TEXT_NODE:
            content.append(node.getNodeValue());
            break;
        }//from  w w  w .ja v a  2s  .  c o m
    }
    return content.toString().trim();
}

From source file:Main.java

private static String prettyPrintDom(Node node, String indent, boolean isRoot, boolean escapeStrings) {
    String ret = "";
    switch (node.getNodeType()) {

    case Node.DOCUMENT_NODE:
        // recurse on each child
        NodeList nodes = node.getChildNodes();
        if (nodes != null) {
            for (int i = 0; i < nodes.getLength(); i++) {
                ret += prettyPrintDom(nodes.item(i), indent, isRoot, escapeStrings);
            }//from   w  w w  . jav a2 s.  c o  m
        }
        break;

    case Node.ELEMENT_NODE:
        String name = node.getNodeName();
        ret += indent + "<" + name;
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node current = attributes.item(i);
            ret += " " + current.getNodeName() + "=\""
                    + ((escapeStrings) ? escapeStringForXML(current.getNodeValue()) : current.getNodeValue())
                    + "\"";
        }
        ret += ">";

        // recurse on each child
        NodeList children = node.getChildNodes();
        if (children != null) {
            for (int i = 0; i < children.getLength(); i++) {
                String tmp = prettyPrintDom(children.item(i), indent + ((isRoot) ? "" : BI), false,
                        escapeStrings);
                if (!tmp.replaceAll("[\\s]+", "").equals(""))
                    if (tmp.endsWith("\n"))
                        if (ret.endsWith("\n"))
                            ret += tmp;
                        else
                            ret += "\n" + tmp;
                    else
                        ret += tmp;
            }
        }
        if (ret.endsWith("\n"))
            ret += indent + "</" + name + ">\n";
        else
            ret += "</" + name + ">\n";
        break;

    case Node.TEXT_NODE:
        ret += (escapeStrings) ? escapeStringForXML(node.getNodeValue()) : node.getNodeValue();
        break;

    case Node.COMMENT_NODE:
        ret += "<!-- " + node.getNodeValue() + " -->";
        break;
    }
    return ret;
}

From source file:com.ewcms.common.io.HtmlStringUtil.java

public static String getPureText(Node node) {
    if (!node.hasChildNodes() && isTextNode(node))
        return node.getNodeValue();
    if (isFiltered(node))
        return "";
    if (node.hasAttributes()) {
        Node a = node.getAttributes().getNamedItem("style");
        if (a != null) {
            String style = a.getNodeValue();
            Pattern p = Pattern.compile("display\\s*\\:\\s*none", 2);
            if (p.matcher(style).find())
                return "";
        }/*from  w  w  w .ja  va  2  s  . c o m*/
    }
    StringBuffer sb = new StringBuffer();
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
        Node child = list.item(i);
        String name = child.getNodeName();
        sb.append(getPureText(child));
        sb.append(" ");
        if (name.equals("TR") || name.equals("P") || name.equals("DIV"))
            sb.append("\n");
    }

    return sb.toString();
}

From source file:Main.java

/** Get string value of an element.
 *  @param element Element/*from  w w  w  .  j  av a2  s.co  m*/
 *  @return String of the node. Empty string if nothing found.
 */
public static String getString(final Element element) {
    final Node text = element.getFirstChild();
    if (text == null) // <empty /> node
        return "";
    if ((text.getNodeType() == Node.TEXT_NODE || text.getNodeType() == Node.CDATA_SECTION_NODE))
        return text.getNodeValue();
    return "";
}

From source file:Main.java

public static int outputNode(Node outputNode, PrintWriter outputWriter, int curPos) {
    NodeList nodes = outputNode.getChildNodes();
    int curNodeNum;
    if (outputNode.getNodeType() == Node.TEXT_NODE) {
        outputWriter.print(outputNode.getNodeValue());
    } else {/*from w  w w . ja v a 2s .c o  m*/
        if (outputNode.getNodeName().equals("p")) {
            outputWriter.println();
        }

        for (curNodeNum = 0; curNodeNum < nodes.getLength(); curNodeNum++) {
            Node curNode = nodes.item(curNodeNum);
            curPos = outputNode(curNode, outputWriter, curPos);
        }

    }
    return (curPos);
}

From source file:Main.java

private static void getChildrenText(NodeList nodeList, StringBuffer buf) {
    int len = nodeList.getLength();
    for (int i = 0; i < len; ++i) {
        Node child = nodeList.item(i);
        while (child != null) {
            short nodeType = child.getNodeType();
            switch (nodeType) {
            case Node.TEXT_NODE:
                buf.append(child.getNodeValue());
                break;
            case Node.ELEMENT_NODE:
                getChildrenText(child.getChildNodes(), buf);
                break;
            }/*from w w w .  j  a  va 2 s .co  m*/
            child = child.getNextSibling();
        }
    }
}

From source file:Main.java

/**
 * Gets a string value of the given attribute
 * @param node// w  w w.ja v  a 2  s  .  c  o m
 * @param attrName
 * @param defaultValue
 * @return
 */
public static String getValue(Node node, String attrName, String defaultValue) {
    Node tmp;
    if (node == null)
        return defaultValue;

    NamedNodeMap attrs = node.getAttributes();
    if (attrs == null)
        return defaultValue;

    String value = (tmp = attrs.getNamedItem(attrName)) != null ? tmp.getNodeValue() : null;

    if (value == null)
        return defaultValue;

    return value;
}

From source file:Main.java

static String getTextValue(Node node) throws SAXException {
    Node textNode = node.getFirstChild();
    if (textNode == null)
        return "";
    if (textNode.getNodeType() != Node.TEXT_NODE)
        throw new SAXException("No text value found for <" + node.getNodeName() + "> node");
    return textNode.getNodeValue();
}