Java XML Node Text Value getTextContent(Node node)

Here you can find the source of getTextContent(Node node)

Description

get Text Content

License

Open Source License

Declaration

public static String getTextContent(Node node) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.stream.IntStream;
import java.util.stream.Stream;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    /**/*w  w w  .  j  a  v  a 2 s.c om*/
     * Get text content of the first child node matching the given node name. Use this method instead of {@link #selectString(String, Object)} whenever xpath support is not required, because it is much faster, especially for large documents.
     *
     * @param childName
     *            search for nodes with this name
     * @param parentNode
     *            search in the child nodes of this nodes
     * @return text content of the child node or null if no child with the given name was found
     */
    public static String getTextContent(String childName, Node parentNode) {
        Node child = getChild(childName, parentNode);

        if (child == null) {
            return null;
        }

        return getTextContent(child);
    }

    public static String getTextContent(Node node) {
        StringBuilder sb = new StringBuilder();

        for (Node textNode : getChildren("#text", node)) {
            sb.append(textNode.getNodeValue());
        }

        return sb.toString().trim();
    }

    /**
     * @param nodeName
     *            search for nodes with this name
     * @param parentNode
     *            search in the child nodes of this nodes
     * @return text content of the child node or null if no child with the given name was found
     */
    public static Node getChild(String nodeName, Node parentNode) {
        if (parentNode == null) {
            return null;
        } else {
            return stream(parentNode.getChildNodes()).filter(n -> nodeName.equals(n.getNodeName())).findFirst()
                    .orElse(null);
        }
    }

    public static Node[] getChildren(String nodeName, Node parentNode) {
        if (parentNode == null) {
            return new Node[0];
        } else {
            return stream(parentNode.getChildNodes()).filter(n -> nodeName.equals(n.getNodeName()))
                    .toArray(Node[]::new);
        }
    }

    public static Stream<Node> stream(NodeList nodes) {
        return IntStream.range(0, nodes.getLength()).mapToObj(nodes::item);
    }
}

Related

  1. getTextContent(Node e)
  2. getTextContent(Node element)
  3. getTextContent(Node node)
  4. getTextContent(Node node)
  5. getTextContent(Node node)
  6. getTextContent(Node node)
  7. getTextContent(Node node)
  8. getTextContent(Node node)
  9. getTextContent(Node node)