Android examples for XML:XML Element
Retrieves the text content of the specified sub element for the given XML element.
//package com.java2s; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /**/*from ww w. j a v a 2 s . c o m*/ * Retrieves the text content of the specified sub element for the given element. * * @param elem The element whose subelement text contents is to be retrieved. * @param tagName Name of the subelement. * @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 String getSubElementContents(Element elem, String tagName) { Element child = getChildElement(elem, tagName); if (child != null) { return child.getTextContent(); } else { return null; } } /** * 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; } }