[jdom-interest] swapping nodes and their children?

Alex Rosen arosen at novell.com
Mon Dec 2 22:49:19 PST 2002

Instead of:

      List anchorList = anchor.getContent();

do this:

      List anchorList = new ArrayList(anchor.getContent());

This makes a copy of the list of children from anchor, then ensures that anchor has no children (thus detaching all the children), and then adds the children to heading.


>>> Greg Wilson <Greg.Wilson at baltimore.com> 12/02/02 03:26PM >>>
Hi, folks.  I have an HTML document which contains both:

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


<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()'.)


    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

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

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

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.


This footnote confirms that this email message has been swept by 
Baltimore MIMEsweeper for Content Security threats, including
computer viruses.
To control your jdom-interest membership:

More information about the jdom-interest mailing list