Java tutorial
//package com.java2s; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Static helper function to get the element data of the specified node. * * @param node * the node where the text data resides; may be <code>null</code> * in which case this funtion will return "" * * @return the complete text of the specified node, or an empty string if * the node has no text or is <code>null</code> */ public static String getElementData(final Node node) { StringBuffer ret = new StringBuffer(); if (node != null) { Node text; for (text = node.getFirstChild(); text != null; text = text.getNextSibling()) { /** * the item's value is in one or more text nodes which are its * immediate children */ if (text.getNodeType() == Node.TEXT_NODE || text.getNodeType() == Node.CDATA_SECTION_NODE) { ret.append(text.getNodeValue()); } else { if (text.getNodeType() == Node.ENTITY_REFERENCE_NODE) { ret.append(getElementData(text)); } } } } return ret.toString(); } /** * Gets the text value of the specified element. * * @param root * the root of the element whose text is to be retrieved; assumed * not to be <code>null</code>. * @param elementName * the name of the element whose text is to be retrieved. * * @return the retrieved text value of the specified element or null if root * has no given element. */ public static String getElementData(final Element root, final String elementName) { NodeList nodes = root.getElementsByTagName(elementName); if (nodes.getLength() < 1) { return null; } return getElementData(nodes.item(0)); } }