Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

When doing an XSL-T transformation, you get org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.. Usually, this is being caused by whitespace or other characters being added to the beginning of the document before any other node has been added.

Example

When transforming this document...

Code Block
langxml
<?xml version="1.0">
<root>
  <child>
    child text
    <grandchild>my text</grandchild>
  </child>
</root>

...with this XSL stylesheet, which looks fine at first glance, ...

Code Block
langxml
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="/root/child/grandchild">
    <newroot>
      <newchild>
        <newgrandchild>We left out the child text this time</newgrandchild>
      </newchild>
    </newroot> 
  </xsl:template>

</xsl:stylesheet>

...you end up with a resulting document that has leading characters and white space, which causes the DOMException

Code Block
langxml
<?xml version="1.0" encoding="UTF-8"?>

  
    child text
    <newroot>
<newchild>
<newgrandchild>We left out the child text this time</newgrandchild>
</newchild>
</newroot>

Solution

The easiest way to resolve this, is by making sure that you always have a template that matches the source root element and creates the target document's root element. In this case:

Code Block
langxml
  <xsl:template match="root">
    <newroot>
      <xsl:apply-templates/>
    </newroot>
  </xsl:template>