<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="2.0"
  xmlns:f="http://f/" exclude-result-prefixes="f">

<xsl:output method="xml" indent="no"/>

<xsl:param name="input" required="yes"/>

<xsl:template match="person[@gender eq 'M']">
  <xsl:apply-templates select="." mode="man"/>
</xsl:template>

<xsl:template match="person[@gender eq 'F']">
  <xsl:apply-templates select="." mode="woman"/>
</xsl:template>

<xsl:template match="person" mode="man">
  <man name="{name}">
    <sons>
      <xsl:apply-templates select="children/person[@gender eq 'M']"
mode="man"/>
    </sons>
    <daughters>
      <xsl:apply-templates select="children/person[@gender eq 'F']"
mode="woman"/>
    </daughters>

  </man>
</xsl:template>

<xsl:template match="person" mode="woman">
  <woman name="{name}">
    <sons>
      <xsl:apply-templates select="children/person[@gender eq 'M']"
mode="man"/>
    </sons>
    <daughters>
      <xsl:apply-templates select="children/person[@gender eq 'F']"
mode="woman"/>
    </daughters>
  </woman>
</xsl:template>

<xsl:function name="f:topLevelPersons">
 <xsl:copy-of select="doc($input)/*/person"
                   saxon:read-once="yes"
                   xmlns:saxon="http://saxon.sf.net/"/>
</xsl:function>

<xsl:template name="main">
  <xsl:apply-templates select="f:topLevelPersons()"/>
</xsl:template>

</xsl:stylesheet>

