Removing all text nodes from a given node

Discussion in 'Java' started by Narokman, Jan 4, 2005.

  1. Narokman

    Narokman Guest

    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.
     
    Narokman, Jan 4, 2005
    #1
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    0
    Views:
    1,922
  2. Michael Reiche
    Replies:
    3
    Views:
    11,439
    Michael Reiche
    Feb 5, 2004
  3. Tjerk Wolterink
    Replies:
    2
    Views:
    1,726
    Dimitre Novatchev
    Aug 24, 2006
  4. Replies:
    1
    Views:
    1,441
    Joe Kesselman
    Nov 1, 2006
  5. Replies:
    0
    Views:
    623
  6. chiara
    Replies:
    6
    Views:
    755
    Barry Schwarz
    Oct 6, 2005
  7. thecolour
    Replies:
    0
    Views:
    529
    thecolour
    Jun 26, 2007
  8. thecolour
    Replies:
    2
    Views:
    586
    thecolour
    Jun 27, 2007
Loading...