The error message you get actually speaks for itself. You cannot add attributes if child nodes are already assigned to a node.
Simply separate applying a template to all attributes @*
from applying a template to all potential child nodes node()
. Note that this captures not only child elements.
By the way, I could reproduce your error message only with Saxon 9.5.1 but not with Saxon 6.5.5 and Xalan 2.7.1.
Stylesheet
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="d[contains(@atr1, 'MGR_')]">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:attribute name="atr2">
<xsl:choose>
<xsl:when test="@atr2">
<xsl:value-of select="concat('#{', substring(@atr2,3,string-length(@atr2)-3), ' and not ', substring(@atr1,3))" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="concat('#{not ', substring(@atr1,3))" />
</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>