Java examples for XML:DOM Node
Retrieves an XML element from the given start node by following the specified sequential path of elements.
//package com.java2s; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /**/*from w w w.j a va2 s . c o m*/ * Retrieves an XML element from the given start node by following the specified * sequential path of elements. * * @param start The context node from which the path is to be evaluated. * @param path A list element names that defines the path to the target element. * @return The element at the end of the path or null if the path does not exist. */ public static Element getElementByPath(Element start, String... path) { Element contextNode = start; int index = 0; while (index < path.length && contextNode != null) { contextNode = getChildElement(contextNode, path[index++]); } return contextNode; } /** * Retrieves the child element with the specified tag name for the given element. * * @param elem The element whose child element is to be retrieved. * @param tagName Name of the child element. * @pre elem != null && tagName != null && !tagName.equals("") * @return The text contents of the specified sub element, or null if the subelement * does not exist. */ public static Element getChildElement(Element elem, String tagName) { NodeList children = elem.getChildNodes(); Element childElement = null; int index = 0; while (childElement == null && index < children.getLength()) { Node child = children.item(index); if (child.getNodeType() == Node.ELEMENT_NODE && ((Element) child).getTagName().equals(tagName)) { childElement = (Element) child; } else { index++; } } return childElement; } }