Java examples for XML:XML Element Child
Retrieves the child XML element with the specified tag name for the given element.
//package com.java2s; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /**/*from w ww.j a v a2 s . c o m*/ * 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; } }