If you want to make the transform apply to all elements, you need a template to match all elements, as opposed to having a template that just matches the specific "foo" element
<xsl:template match="*">
Note that, you would have to change the current template that matches "node()" to exclude elements:
<xsl:template match="node()[not(self::*)]|@*">
Within this template, you will also need code to select the attributes, because your "foo" template at the moment will ignore them (<xsl:apply-templates />
does not select attributes).
Actually, looking at your requirements, items 1 to 3 can all be done with a single XSLT. For example, to remove comments, you could just ignore it from the template that currently matches node()
<xsl:template match="node()[not(self::comment())][not(self::*)]|@*">
Try the following XSLT, will should achieve points 1 to 3
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()[not(self::comment())][not(self::*)]|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates select="@*">
<xsl:sort select="name()"/>
</xsl:apply-templates>
<xsl:apply-templates>
<xsl:sort select="name()"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
EDIT: The template <xsl:template match="node()[not(self::comment())][not(self::*)]|@*">
can actually be replaced with just <xsl:template match="processing-instruction()|@*">
which may increase readability. This is because "node()" matches elements, text nodes, comments and processing instructions. In your XSLT, elements are picked up by the other template, text nodes by the built-in template, and comments you want to ignore, leaving just processing instructions.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…