Java XML Node Path extractPaths(Node node, String[] path)

Here you can find the source of extractPaths(Node node, String[] path)

Description

Returns all nodes at the bottom of path from node.

License

Apache License

Parameter

Parameter Description
node Node to apply path to
path Path to apply

Return

All nodes at bottom of path. List may be empty but not null.

Declaration

static public List<Node> extractPaths(Node node, String[] path) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

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

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

public class Main {
    /**/*from  w  w w  . j  av a 2 s.c  o  m*/
     *  Returns all nodes at the bottom of path from node.
     * If element begins with '@', indicates an attribute, eg "@id"
     * The '#text' element indicates that the node has a single text child.
     * @param node    Node to apply path to
     * @param path    Path to apply
     * @return        All nodes at bottom of path. List may be empty but not null.
     */
    static public List<Node> extractPaths(Node node, String[] path) {
        List<Node> result = new ArrayList<Node>();
        result.add(node);
        for (int i = 0; i < path.length; i++) {
            List<Node> children = new ArrayList<Node>();
            for (int j = 0; j < result.size(); j++)
                children.addAll(extractNodes((Node) result.get(j), path[i]));
            result = children;
        }
        return result;
    }

    /**
     *  Returns all nodes at the bottom of path from node.
     * If element begins with '@', indicates an attribute, eg "@id"
     * The '#text' element indicates that the node has a single text child.
     * @param node    Node to apply path to
     * @param path    Path to apply
     * @return        All Nodes at bottom of path. List may be empty, but not null.
     */
    static public List<Node> extractNodes(Node node, String path) {
        if (node == null)
            return new ArrayList<Node>();
        List<Node> result = new ArrayList<Node>();
        NodeList list = node.getChildNodes();
        if (path.equals("#text"))
            result.add(node.getFirstChild());
        else if (path.charAt(0) == '@')
            result.add(node.getAttributes().getNamedItem(path.substring(1)));
        else
            for (int j = 0; j < list.getLength(); j++)
                if (list.item(j).getNodeType() == Node.ELEMENT_NODE && list.item(j).getNodeName().equals(path))
                    result.add(list.item(j));
        return result;
    }
}

Related

  1. addElementPath(Node element, String path)
  2. createAndAppendNode(Node root, String path)
  3. extractNodes(Node node, String path)
  4. extractPath(Node node, String[] path)
  5. getCompletePathForANode(Node objNode)
  6. getContent(Node n, String path)
  7. getDescendant(Node node, String path)
  8. getElementViaPath(Node node, String path)