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...
<?xml version="1.0"> <root> <child> child text <grandchild>my text</grandchild> </child> </root>
...with this XSL stylesheet, which looks fine at first glance, ...
<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
<?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:
<xsl:template match="root">
<newroot>
<xsl:apply-templates/>
</newroot>
</xsl:template>
{code)