Hi
I wrote the
following function to emilate XML4J's TXElements.getText(), which returned a
string containing the text of all child nodes of a particular element. This
might be of
some
use to you. Since comments are a subclass of CharacterData this function will
include comments in the string returned.
/** Return all text
associated with this Node and its children without considering entities.
* @param node - the node providing the context for the search * @returns Text associated with all children, or "" if no children. */ public static final java.lang.String getText(org.w3c.dom.Node node) { //Initialise the string buffer so we'll at least return "". StringBuffer sb = new StringBuffer(""); try { NodeList nl = node.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { //Is it a subclass of org.w3c.dom.CharacterData e.g. Text, CDATA Section, Comment etc.. if (nl.item(i) instanceof org.w3c.dom.CharacterData) { sb.append(((org.w3c.dom.CharacterData)nl.item(i)).getData()); } //Recursively examine the children of this node sb.append(getText(nl.item(i))); } } catch(java.lang.Exception e) { //Needs to be handled ? e.printStackTrace(); } //Convert the contents to a String return sb.toString(); } Regards
Anthony Dodd
|
- Newby question: Get Text of a Node Nathan Troxler
- Re: Newby question: Get Text of a Node Andy Heninger
- Anthony Dodd