Example usage for org.w3c.dom Node TEXT_NODE

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

Introduction

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

Prototype

short TEXT_NODE

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

Click Source Link

Document

The node is a Text node.

Usage

From source file:Main.java

/**
 * The method inserts end-of-line+indentation Text nodes where indentation is necessary.
 *
 * @param node - node to be pretty formatted
 * @param identLevel - initial indentation level of the node
 * @param ident - additional indentation inside the node
 *//*  w w  w.  j av a 2  s.com*/
private static void prettyFormat(Node node, String identLevel, String ident) {
    NodeList nodelist = node.getChildNodes();
    int iStart = 0;
    Node item = nodelist.item(0);
    if (item != null) {
        short type = item.getNodeType();
        if (type == Node.ELEMENT_NODE || type == Node.COMMENT_NODE) {
            Node newChild = node.getOwnerDocument().createTextNode(EOL_XML + identLevel + ident);
            node.insertBefore(newChild, item);
            iStart = 1;
        }
    }
    for (int i = iStart; i < nodelist.getLength(); i++) {
        item = nodelist.item(i);
        if (item != null) {
            short type = item.getNodeType();
            if (type == Node.TEXT_NODE && item.getNodeValue().trim().length() == 0) {
                if (i + 1 < nodelist.getLength()) {
                    item.setNodeValue(EOL_XML + identLevel + ident);
                } else {
                    item.setNodeValue(EOL_XML + identLevel);
                }
            } else if (type == Node.ELEMENT_NODE) {
                prettyFormat(item, identLevel + ident, ident);
                if (i + 1 < nodelist.getLength()) {
                    Node nextItem = nodelist.item(i + 1);
                    if (nextItem != null) {
                        short nextType = nextItem.getNodeType();
                        if (nextType == Node.ELEMENT_NODE || nextType == Node.COMMENT_NODE) {
                            Node newChild = node.getOwnerDocument()
                                    .createTextNode(EOL_XML + identLevel + ident);
                            node.insertBefore(newChild, nextItem);
                            i++;
                            continue;
                        }
                    }
                } else {
                    Node newChild = node.getOwnerDocument().createTextNode(EOL_XML + identLevel);
                    node.appendChild(newChild);
                    i++;
                    continue;
                }
            }
        }
    }
}

From source file:Main.java

private static String getTextContent(Element element) {
    if (element == null) {
        return null;
    }// w w w. j  a va2s  .c  om
    Node textNode = element.getFirstChild();
    if (textNode == null) {
        return "";
    }
    if (textNode.getNodeType() != Node.TEXT_NODE) {
        throw new RuntimeException("Element " + element.getTagName() + "does not have text content");
    }
    return textNode.getNodeValue();
}

From source file:com.microsoft.tfs.util.xml.DOMUtils.java

/**
 * A DOM helper method to get the text contents of a {@link Node}. If the
 * {@link Node} is a text node ({@link Node#TEXT_NODE}) or a CDATA section
 * node ({@link Node#CDATA_SECTION_NODE}), the node's value is returned. If
 * the {@link Node} is a element node ({@link Node#ELEMENT_NODE}), the node
 * value of any <i>direct child</i> nodes that are text or CDATA sections
 * are appended together and returned. If the node is not of any of the
 * above types, an empty string is returned.
 *
 * @param node//from w  ww.  j a v a2  s.c  o m
 *        the {@link Node} to get text for (must not be <code>null</code>)
 * @return the text (never <code>null</code> but may be an empty
 *         {@link String})
 */
public static String getText(final Node node) {
    Check.notNull(node, "node"); //$NON-NLS-1$

    final int type = node.getNodeType();

    if (Node.ELEMENT_NODE == type) {
        final NodeList children = node.getChildNodes();
        final StringBuffer buffer = new StringBuffer();
        final int length = children.getLength();
        for (int i = 0; i < length; i++) {
            final Node child = children.item(i);
            final int childType = child.getNodeType();
            if (Node.TEXT_NODE == childType || Node.CDATA_SECTION_NODE == childType) {
                buffer.append(child.getNodeValue());
            }
        }
        return buffer.toString();
    }

    if (Node.TEXT_NODE == type || Node.CDATA_SECTION_NODE == type) {
        return node.getNodeValue();
    }

    return ""; //$NON-NLS-1$
}

From source file:edu.duke.cabig.c3pr.webservice.integration.XMLUtils.java

/**
 * Does deep comparison of two DOM trees represented by the given
 * {@link Element}s. Elements are considered root nodes of the trees. <br>
 * <br>//  ww  w . j  a v  a2 s .  com
 * This version of the method will <b>only</b> process elements of types
 * {@link Node#ELEMENT_NODE},{@link Node#TEXT_NODE},
 * {@link Node#CDATA_SECTION_NODE}; others will be ignored. Content of text
 * nodes is normalized before comparison. <br>
 * <br>
 * When comparing two elements, their local names, namespaces, and
 * attributes (except <code>xmlns* and xsi:type</code>) are accounted for. <br>
 * <br>
 * Due to issues with using
 * <code>setIgnoringElementContentWhitespace(true)</code>, which does not
 * seem to work, this method will throw out empty text nodes when comparing
 * children.
 * 
 * @since 1.0
 * @param e1
 * @param e2
 * @return
 */
public static boolean isDeepEqual(Node n1, Node n2) {
    if (!StringUtils.equals(n1.getLocalName(), n2.getLocalName())) {
        log.info("Node local names are not equal: " + n1.getLocalName() + " " + n2.getLocalName());
        return false;
    }
    if (!StringUtils.equals(n1.getNamespaceURI(), n2.getNamespaceURI())) {
        log.info("Node namespaces are not equal: " + n1.getNamespaceURI() + " " + n2.getNamespaceURI());
        return false;
    }
    if (n1.getNodeType() != n2.getNodeType()) {
        log.info("Node types are not equal: " + n1.getNodeType() + " " + n2.getNodeType());
        return false;
    }
    // check attributes equality.
    NamedNodeMap attrs1 = n1.getAttributes();
    NamedNodeMap attrs2 = n2.getAttributes();
    if (!isEqual(attrs1, attrs2)) {
        return false;
    }

    short nodeType = n1.getNodeType();
    switch (nodeType) {
    case Node.ELEMENT_NODE:
        return isDeepEqual(filterOutEmptyTextNodes(n1.getChildNodes()),
                filterOutEmptyTextNodes(n2.getChildNodes()));
    case Node.TEXT_NODE:
        return isTextNodeEqual(n1, n2);
    case Node.CDATA_SECTION_NODE:
        return isTextNodeEqual(n1, n2);
    default:
        break;
    }
    return true;
}

From source file:Main.java

/**
 * Locate the first text node at any level below the given node. If the
 * ignoreEmpty flag is true, we will ignore text nodes that contain only
 * whitespace characteres./*from w w w.j a va 2s  .  c om*/
 * <p/>
 * Note that if you're trying to extract element content, you probably don't
 * want this since parser's can break up pcdata into multiple adjacent text
 * nodes. See getContent() for a more useful method.
 */
private static Text findText(Node node, boolean ignoreEmpty) {

    Text found = null;

    if (node != null) {

        if (node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.CDATA_SECTION_NODE) {

            Text t = (Text) node;
            if (!ignoreEmpty) {
                found = t;
            } else {
                String s = t.getData().trim();
                if (s.length() > 0) {
                    found = t;
                }
            }
        }

        if (found == null) {

            for (Node child = node.getFirstChild(); child != null
                    && found == null; child = child.getNextSibling()) {

                found = findText(child, ignoreEmpty);
            }
        }
    }

    return found;
}

From source file:Main.java

public static void cleanText(Node node) {
    try {/*from  w ww  .  ja  v a2 s . co  m*/
        NodeList childNodes = node.getChildNodes();
        int noChildren = childNodes.getLength();
        Node n = null;
        short type = 0;
        Vector rem = new Vector();
        for (int i = 0; i < noChildren; i++) {
            n = childNodes.item(i);
            type = n.getNodeType();
            if (type == Node.TEXT_NODE) {
                rem.add(n);
            } else if (type == Node.ELEMENT_NODE) {
                cleanText(n);
            }
        }
        for (int i = 0; i < rem.size(); i++) {
            node.removeChild((Node) rem.get(i));
        }
    } catch (Exception e) {
        //DebugUtil.debug(e);
    }
}

From source file:Main.java

/**
 * Returns String representation of specified xml node.
 *
 * @param node   the specified xml node//  ww  w .j  a v  a 2s  .  c om
 * @return string representation of the node
 */
public static String getNodeData(Node node) {
    switch (node.getNodeType()) {
    case Node.DOCUMENT_FRAGMENT_NODE:
    case Node.DOCUMENT_NODE:
    case Node.ELEMENT_NODE: {
        /*for (Node child = node.getFirstChild(); null != child;
          child = child.getNextSibling())*/
        Node child = node.getFirstChild();
        if (child != null)
            return getNodeData(child);
    }
        break;
    case Node.TEXT_NODE:
    case Node.CDATA_SECTION_NODE:
        return node.getNodeValue();
    case Node.ATTRIBUTE_NODE:
        return node.getNodeValue();
    case Node.PROCESSING_INSTRUCTION_NODE:
        break;
    default:
        break;
    }
    return "";
}

From source file:org.apache.solr.kelvin.responseanalyzers.XmlDoclistExtractorResponseAnalyzer.java

public void decode(Map<String, Object> previousResponses) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode response = mapper.createArrayNode();

    if (!previousResponses.containsKey(XmlResponseAnalyzer.XML_DOM)) {
        previousResponses.put(DOC_LIST, response); //empty
        return;/*from ww  w .  j a  va 2 s . c  om*/
    }

    NodeList nodeList = (NodeList) expr.evaluate((Document) previousResponses.get(XmlResponseAnalyzer.XML_DOM),
            XPathConstants.NODESET);

    for (int i = 0; i < nodeList.getLength(); i++) {
        Node doc = nodeList.item(i);
        ObjectNode oDoc = mapper.createObjectNode();
        Node subel = doc.getFirstChild();
        while (subel != null) {
            if (subel.getNodeType() != Node.TEXT_NODE) {
                String fieldName = subel.getAttributes().getNamedItem("name").getNodeValue();
                String elementName = subel.getNodeName();
                if ("arr".equals(elementName)) {
                    ArrayNode multivaluedField = mapper.createArrayNode();
                    Node mvItem = subel.getFirstChild();
                    while (mvItem != null) {
                        multivaluedField.add(mvItem.getTextContent());
                        mvItem = mvItem.getNextSibling();
                    }
                    oDoc.put(fieldName, multivaluedField);
                } else {
                    String value = subel.getTextContent();
                    oDoc.put(fieldName, value);
                }
            }
            subel = subel.getNextSibling();
        }
        response.add(oDoc);
    }
    previousResponses.put(DOC_LIST, response);
}

From source file:Main.java

protected static void print(PrintStream out, Node node) {
    if (node == null)
        return;// w ww.ja v a 2  s. c o  m
    short type = node.getNodeType();
    switch (type) {
    case Node.DOCUMENT_NODE: {
        out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        //out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
        NodeList nodelist = node.getChildNodes();
        int size = nodelist.getLength();
        for (int i = 0; i < size; i++)
            print(out, nodelist.item(i));
        break;
    }

    case Node.DOCUMENT_TYPE_NODE: {
        DocumentType docType = (DocumentType) node;
        out.print("<!DOCTYPE " + getDocumentTypeData(docType) + ">\n");
        break;
    }

    case Node.ELEMENT_NODE: {
        out.print('<');
        out.print(node.getNodeName());
        NamedNodeMap map = node.getAttributes();
        if (map != null) {
            int size = map.getLength();
            for (int i = 0; i < size; i++) {
                Attr attr = (Attr) map.item(i);
                out.print(' ');
                out.print(attr.getNodeName());
                out.print("=\"");
                out.print(normalize(attr.getNodeValue()));
                out.print('"');
            }
        }

        if (!node.hasChildNodes())
            out.print("/>");
        else {
            out.print('>');
            NodeList nodelist = node.getChildNodes();
            int numChildren = nodelist.getLength();
            for (int i = 0; i < numChildren; i++)
                print(out, nodelist.item(i));

            out.print("</");
            out.print(node.getNodeName());
            out.print('>');
        }
        break;
    }

    case Node.ENTITY_REFERENCE_NODE: {
        NodeList nodelist = node.getChildNodes();
        if (nodelist != null) {
            int size = nodelist.getLength();
            for (int i = 0; i < size; i++)
                print(out, nodelist.item(i));

        }
        break;
    }

    case Node.CDATA_SECTION_NODE: {
        out.print(normalize(node.getNodeValue()));
        break;
    }

    case Node.TEXT_NODE: {
        out.print(normalize(node.getNodeValue()));
        break;
    }

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

    case Node.COMMENT_NODE: {
        out.print("<!--");
        out.print(node.getNodeValue());
        out.print("-->");
        break;
    }

    default: {
        out.print(normalize(node.getNodeValue()));
        break;
    }
    }
    out.flush();
}

From source file:DomUtil.java

/**
 * Set or replace the text value//from w w  w.j a  v  a  2 s.  com
 */
public static void setText(Node node, String val) {
    Node chld = DomUtil.getChild(node, Node.TEXT_NODE);
    if (chld == null) {
        Node textN = node.getOwnerDocument().createTextNode(val);
        node.appendChild(textN);
        return;
    }
    // change the value
    chld.setNodeValue(val);
}