Search code examples
jythondom4j

Is adding elements between elements with Jython and dom4j possible?


Just playing with dom4j, excellent. I was a PHP developer for a year and half, just got a new job and started playing around with Jython now I have spare time, its a great language. Was thinking about trying to add a element in between element, example below:

<div id="content">
    <p>Some text in here</p>
    <!--New p tag here-->
    <p>Some text in here</p>
</div>

Is it possible to insert another p tag in between the two without converting the DOM to a string and back to DOM again as this is the only way I have been able to do it?


Solution

  • I don't know much about dom4j specifically, but I would do it like this:

    1. Copy all child nodes of div#content into a list, then delete its children.
    2. Insert the first node back into the div#content node.
    3. Insert the new p node into the div#content node.
    4. Insert the last node back into the div#content node.

    I don't know what this would be in terms of the DOM, but if nodes are represented as Jythonic objects, then it should be easy to do this.