Removing all text nodes from a given node

From: Narokman (naerok1999_at_yahoo.com)
Date: 01/04/05


Date: 4 Jan 2005 13:23:36 -0800

I've written a method that is supposed to remove all text nodes from a
given node and also from its child nodes. The given node is, for
example,
created from following XML:
--------------
<?xml version="1.0" encoding="utf-8" ?>

<L1>L1 Text
<L2>L2 Text
<L3>L3 Text</L3>
</L2>
<L2_1>L2_1 Text</L2_1>
<L2_2>L2_2 Text</L2_2>
</L1>
--------------

The method I've written is :

--------------
public static void removeEmptyText(org.w3c.dom.Node n) {
org.w3c.dom.NodeList nodeList = n.getChildNodes();

for (int i = 0; i < nodeList.getLength(); i++) {
org.w3c.dom.Node node = nodeList.item(i);
int type = node.getNodeType();

// if (type == ELEMENT_TYPE) {
if (node.hasChildNodes()) {
removeEmptyText(node);
}else if (type == TEXT_TYPE) {
n.removeChild(node);
}
}//End of for-loop
}
--------------

This method only works for removing text nodes in the "L1" level.
It fails to remove text nodes in child nodes of "L1".
Any ideas?
If anybody has better way to remove text nodes from a node, I would
also really appreciated.

Thanks.



Relevant Pages

  • rexml: replace several text nodes by a single one
    ... I want to replace the text child nodes of an REXML::Element by a new, ... # iterate all elements, call delete_element: fails, because ... # MAGIC CODE GOES HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ... I don't think that setting all text nodes to zero-length string values is a _good_ solution. ...
    (comp.lang.ruby)
  • Re: Removing all children from an element
    ... Matthias Watermann wrote: ... list of child nodes would only loose its last entry. ... removing the first list entry would require readjusting all the other ...
    (comp.lang.javascript)
  • Re: Is there a way to delete a subset (continous) of child nodes?
    ... a subset of the child nodes of a given DOM parent node? ... // note it does not mean, start removing all nodes from node 10 ...
    (comp.lang.javascript)