Here you can find the source of getElementViaPath(Node node, String path)
Parameter | Description |
---|---|
node | the top of the tree to search. |
path | the path from the top of the tree to the desired element. |
public static Element getElementViaPath(Node node, String path)
//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; } }