Java XML Node Path getElementViaPath(Node node, String path)

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

Description

Get an element specified by a starting node and a path string.

License

Open Source License

Parameter

Parameter Description
node the top of the tree to search.
path the path from the top of the tree to the desired element.

Return

the first element matching the path, or null if no element exists at the path location or if the starting node is not an element.

Declaration

public static Element getElementViaPath(Node node, String path) 

Method Source Code

//package com.java2s;
/*---------------------------------------------------------------
*  Copyright 2005 by the Radiological Society of North America
*
*  This source software is released under the terms of the
*  RSNA Public License (http://mirc.rsna.org/rsnapubliclicense)
*----------------------------------------------------------------*/

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

public class Main {
    /**/*from  w  w  w  . j av a 2s .c o m*/
     * Get an element specified by a starting node and a path string.
     * If the starting node is a Document, use the document element
     * as the starting point.
     * A path to an element has the form: elem1/.../elemN
     * @param node the top of the tree to search.
     * @param path the path from the top of the tree to the desired element.
     * @return the first element matching the path, or null if no element
     * exists at the path location or if the starting node is not an element.
     */
    public static Element getElementViaPath(Node node, String path) {
        if (node instanceof Document)
            node = ((Document) node).getDocumentElement();
        if (!(node instanceof Element))
            return null;
        int k = path.indexOf("/");
        String firstPathElement = path;
        if (k > 0)
            firstPathElement = path.substring(0, k);
        if (node.getNodeName().equals(firstPathElement)) {
            if (k < 0)
                return (Element) node;
            path = path.substring(k + 1);
            NodeList nodeList = ((Element) node).getChildNodes();
            Node n;
            for (int i = 0; i < nodeList.getLength(); i++) {
                n = nodeList.item(i);
                if ((n instanceof Element) && ((n = getElementViaPath(n, path)) != null))
                    return (Element) n;
            }
        }
        return null;
    }
}

Related

  1. extractPath(Node node, String[] path)
  2. extractPaths(Node node, String[] path)
  3. getCompletePathForANode(Node objNode)
  4. getContent(Node n, String path)
  5. getDescendant(Node node, String path)
  6. getFullPath(Node node)
  7. getIndividualPath(Node individual)
  8. getMatchingNodes(Node node, String[] nodePath, int cur, List res)
  9. getNode(Node node, String... nodePath)