Java tutorial
//package com.java2s; //License from project: Apache License import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Get the element text value. Locate the text node and return * its contents. * * @param element The element to get the name for * @return The text value */ public static String getElementTextValue(Element element) { String value = ""; // get the text node Node node = getElementTextNode(element); if (node != null) { value = node.getNodeValue(); } // if the entire string is whitespace ignore this // but don't trim the whitespace if it is there String testValue = value.trim(); if (testValue.length() <= 0) { value = ""; } return (value); } /** * Get the element text node. Locate the text node and return it. For example; * <element>this is the text node</element> * * @param element The element to get the text node for * @return The text node */ public static Node getElementTextNode(Element element) { Node textNode = null; // go through each child element Node node; short nodeType; NodeList children = element.getChildNodes(); for (int ii = 0; ii < children.getLength(); ii++) { node = children.item(ii); nodeType = node.getNodeType(); if (nodeType == Node.TEXT_NODE) { textNode = node; break; } else if (nodeType == Node.CDATA_SECTION_NODE) { textNode = node; break; } } return (textNode); } }