Java XML Node Text Value getSingleNodeTextContent(Node node, String path)

Here you can find the source of getSingleNodeTextContent(Node node, String path)

Description

get Single Node Text Content

License

Open Source License

Parameter

Parameter Description
node a parameter
path a parameter

Declaration

public static String getSingleNodeTextContent(Node node, String path) 

Method Source Code

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

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Node;

public class Main {

    public static String getSingleNodeTextContent(Node node, String path) {
        List nodeList = getNodes(node, path);

        if ((nodeList.size() > 0) && (nodeList.get(0) != null)
                && (((Node) nodeList.get(0)).getTextContent().length() > 0)) {
            return ((Node) nodeList.get(0)).getTextContent();
        }//from  w  ww  .  j a v  a  2  s.  com
        return null;
    }

    public static List<Node> getNodes(Node node, String path) {
        ArrayList nodeList = new ArrayList();

        ArrayList pathList = new ArrayList();
        String[] pathArray = path.split("/");
        for (int i = 0; i < pathArray.length; i++) {
            if (pathArray[i].equals(""))
                continue;
            pathList.add(pathArray[i]);
        }

        for (int i = 0; i < pathList.size(); i++) {
            StringBuffer restPath = new StringBuffer();
            for (int k = i + 1; k < pathList.size(); k++) {
                restPath.append("/").append((String) pathList.get(k));
            }

            for (int j = 0; j < node.getChildNodes().getLength(); j++) {
                if (!node.getChildNodes().item(j).getNodeName().equals(pathList.get(i)))
                    continue;
                if (restPath.length() == 0) {
                    nodeList.add(node.getChildNodes().item(j));
                } else {
                    nodeList.addAll(getNodes(node.getChildNodes().item(j), restPath.toString()));
                }
            }

        }

        return nodeList;
    }
}

Related

  1. getPropertiesFromXML(Node propNode)
  2. getPropText(Node node)
  3. getRawContent(Node n)
  4. getSimpleElementText(final Node node)
  5. getSimpleNodeValue(Node node)
  6. getStrElementValue(Node node)
  7. getString(final Node node, final String default_value)
  8. getString(Node node)
  9. getStringValue(NamedNodeMap values, String name)