The short answer is that in the following template.
<xsl:template match="//T">
<xsl:apply-templates
select="document('lookup.xml')//AB/pa[(_at_)prefnum=current()/pref]/*" mode="p">
<xsl:with-param name="id" select="@id" />
</xsl:apply-templates>
<xsl:apply-templates select="*" />
</xsl:template>
It does not create any output nodes. Therefore the p output nodes are all
generated within the template for match="*" and mode="p". Hence the p nodes
must all be closed prior to processing the current T input node's children.
You can correct that by moving the first p output node into the match="T"
template, and include the apply-templates inside of that p node. Of course,
this looks slightly odd and requires that your lookup tree be of the
following form:
<pa prefnum="1">
<XXXX>
<YYYY />
<ZZZZ />
</XXXX>
</pa>
and NOT:
<pa prefnum="1">
<XXXX>
<YYYY />
<ZZZZ />
</XXXX>
<AAAA>
<BBBB />
<CCCC />
</AAAA>
</pa>
Here is a transform which does pretty much all you want. I did use a global
variable rather than opening the lookup document everywhere.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" />
<xsl:variable name="lookUp">
<xsl:copy-of select="document('lookup.xml')"/>
</xsl:variable>
<xsl:template match="/">
<Root>
<xsl:apply-templates />
</Root>
</xsl:template>
<xsl:template match="T">
<xsl:variable name="nodeLookup">
<xsl:value-of
select="name($lookUp/AB/pa[(_at_)prefnum=current()/pref]/*)"/>
</xsl:variable>
<xsl:variable name="newid" select="concat(translate(@id,' ','_'),
1)"/>
<p c="{$nodeLookup}" id="{$newid}">
<xsl:apply-templates
select="$lookUp/AB/pa[(_at_)prefnum=current()/pref]/*/*" mode="p">
<xsl:with-param name="id" select="$newid" />
</xsl:apply-templates>
<xsl:apply-templates select="*"/>
</p>
</xsl:template>
<xsl:template match="pref"></xsl:template>
<xsl:template mode="p" match="*">
<xsl:param name="id">IDENTIFIER</xsl:param>
<xsl:variable name="idd" select="translate($id,' ','_')"/>
<xsl:variable name="newid" select="concat($idd, position())"/>
<p c="{name()}" id="{$newid}">
<xsl:apply-templates mode="p" select="*">
<xsl:with-param name="id" select="$newid" />
</xsl:apply-templates>
</p>
</xsl:template>
</xsl:stylesheet>
Note that the number is slightly different, because I explicitly removed
text nodes from the apply-templates processing stream.
Steve
LEGAL NOTICE
Unless expressly stated otherwise, this message is confidential and may be
privileged. It is intended for the addressee(s) only. Access to this E-mail by
anyone else is unauthorized. If you are not an addressee, any disclosure or
copying of the contents of this E-mail or any action taken (or not taken) in
reliance on it is unauthorized and may be unlawful. If you are not an
addressee, please inform the sender immediately.