Here you can find the source of getElement(Element elem, String path)
Parameter | Description |
---|---|
elem | The parent/context element |
path | '/' separated path |
public static Element getElement(Element elem, String path)
//package com.java2s; /*// w ww . j a v a 2 s . co m * $Id$ * * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.ArrayList; import java.util.List; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Returns the named descendent. Allows the user * to specify '/' separated path to the child element. e.g. * 'a/b/c'. Note, that in case of multiple children with the * same name, the first child is returned. Returns a null, if * the path does not map to any element. * * @param elem The parent/context element * @param path '/' separated path * @return Named element as per the path. */ public static Element getElement(Element elem, String path) { List elems = getElements(elem, path); if (elems.size() == 0) return null; else return (Element) elems.get(0); } /** * Returns the list of named descendents. Allows the user * to specify '/' separated path to the child element. e.g. * 'a/b/c'. Note, that if 'a' has multiple child elements * named 'b', the method will go to the first 'b' element, * and return all child elements named 'c'. Returns an * empty List if the path does not return any elements. * * @param elem The parent/context element * @param path '/' separated path * @return List of elements as per the path. */ public static List getElements(Element elem, String path) { List list = new ArrayList(); if (elem == null) return list; int ndx = path.indexOf("/"); if (ndx != -1) { Element child = getElement(elem, path.substring(0, ndx)); return getElements(child, path.substring(ndx + 1)); } NodeList nl = elem.getChildNodes(); for (int i = 0, len = nl.getLength(); i < len; i++) { Node node = nl.item(i); if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(path)) { list.add(node); } } return list; } }