Here you can find the source of getChildElementText(final Element elParent, final String childTag)
Parameter | Description |
---|---|
elParent | Parent element. |
childTag | Child element tag. |
public static String getChildElementText(final Element elParent, final String childTag)
//package com.java2s; import org.w3c.dom.CDATASection; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; public class Main { /**//from w ww . j av a 2 s . co m * Returns the text within the child element with the specified tag. * * @param elParent * Parent element. * @param childTag * Child element tag. * @return Child element text. */ public static String getChildElementText(final Element elParent, final String childTag) { final Element elChild = getFirstChildOfType(elParent, childTag); if (elChild == null) { return null; } return getElementText(elChild); } /** * Returns the first child element with the specified tag. * * @param elParent * Parent element. * @param childTag * Child element tag. * @return First child element with the specified tag. */ public static Element getFirstChildOfType(final Element elParent, final String childTag) { for (Node childNode = elParent.getFirstChild(); childNode != null; childNode = childNode .getNextSibling()) { if (childNode.getNodeType() == Node.ELEMENT_NODE) { final Element elChild = (Element) childNode; if (elChild.getTagName().equals(childTag)) { return elChild; } } } return null; } /** * Returns the text within a specified element. Can be optimized for elements with a single text node (common case). * * @param element * Element whose text should be returned. * @return Element's text. */ public static String getElementText(final Element element) { final StringBuffer elementText = new StringBuffer(256); for (Node childNode = element.getFirstChild(); childNode != null; childNode = childNode .getNextSibling()) { if (childNode.getNodeType() == Node.TEXT_NODE) { final Text textNode = (Text) childNode; elementText.append(textNode.getData()); } else if (childNode.getNodeType() == Node.CDATA_SECTION_NODE) { final CDATASection cdataNode = (CDATASection) childNode; elementText.append(cdataNode.getData()); } } return elementText.toString().trim(); } }