[jdom-interest] swapping nodes and their children?

Greg Wilson Greg.Wilson at baltimore.com
Mon Dec 2 12:26:29 PST 2002


Hi, folks.  I have an HTML document which contains both:

<a href="..."><h1>...</h1></a>

and

<h1><a href="...">...</a></h1>

i.e. ordering of anchor and heading tags is inconsistent.
I would like to use JDOM to normalize this, so that (for
example) anchors always wrap headings.  Finding cases to be
corrected is easy; rearranging the nodes is proving to be
more difficult than I expected (and certainly more difficult
than in Python).  The following does *not* work; the last
call to 'setContent()' tells me that the nodes in the list
already have parents.  I suppose I could iterate through the
children of 'anchor', detaching them, then re-attaching them
to the 'heading' node, but surely there has to be an easier
way?  (Especially since content nodes don't have a single
common ancestor with a 'detach()' method, so my detach/attach
loop would have to test each one's type, cast it, and then
call 'detach()'.)

Thanks,
Greg

    protected void swap(Element heading)
    {
      // Get nodes affected
      Element anchor = (Element)heading.getContent().get(0);
      Element parent = heading.getParent();
      List parentList = parent.getContent();

      // Where is the anchor going to sit?
      int headingIndex = parentList.indexOf(heading);

      // Take anchor and heading out of tree
      heading.detach();
      anchor.detach();

      // Put anchor directly beneath parent
      parentList.set(headingIndex, anchor);

      // Move anchor's content to heading, and reattach heading
      heading.setContent(null);
      List anchorList = anchor.getContent();
      heading.setContent(anchorList);
    }


-----------------------------------------------------------------------------------------------------------------
The information contained in this message is confidential and is intended
for the addressee(s) only.  If you have received this message in error or
there are any problems please notify the originator immediately.  The 
unauthorised use, disclosure, copying or alteration of this message is 
strictly forbidden. Baltimore Technologies plc will not be liable for
direct, special, indirect or consequential damages arising from alteration of the
contents of this message by a third party or as a result of any virus being 
passed on.
 
This footnote confirms that this email message has been swept for Content Security threats, including
computer viruses.

http://www.baltimore.com

 
This footnote confirms that this email message has been swept by 
Baltimore MIMEsweeper for Content Security threats, including
computer viruses.



More information about the jdom-interest mailing list