<?xml version='1.0'?>
<xsl:stylesheet
  version='1.0'
  xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>

  <xsl:strip-space elements='*'/>

  <xsl:output
    method='xml'
    indent='yes'/>

  <xsl:template match='/'>
    <xsl:element name='schema'>
      <xsl:apply-templates select='//*'/>
    </xsl:element>
  </xsl:template>

  <xsl:template match='*'>
    <xsl:variable name='parent' select='name()'/>
    <xsl:if
      test='0 = count(
            following::*[name()=$parent])'>
      <xsl:element name='element'>
        <xsl:attribute name='name'>
          <xsl:value-of select='$parent'/>
        </xsl:attribute>
        <xsl:element name='archtype'>
          <xsl:choose>
            <xsl:when
              test='0 != count(
                    //*[name()=$parent]/text())'>
              <xsl:attribute name='content'>mixed</xsl:attribute>
            </xsl:when>
            <xsl:otherwise>
              <xsl:attribute name='order'>choice</xsl:attribute>
              <xsl:attribute name='maxOccurrence'>*</xsl:attribute>
            </xsl:otherwise>
          </xsl:choose>
          <xsl:call-template name='find-kids'>
            <xsl:with-param name='parent'
                          select='$parent'/>
          </xsl:call-template>
        </xsl:element>
      </xsl:element>
    </xsl:if>
  </xsl:template>

  <xsl:template name='find-kids'>
    <xsl:param name='parent'/>
    <xsl:for-each select='//*[name()=$parent]/*'>
      <xsl:variable name='child'>
        <xsl:value-of select='name()'/>
      </xsl:variable>
      <xsl:if
        test='0 = count(
                   following::*[name()=$child]/
                      parent::*[name()=$parent])'>
        <xsl:element name='element'>
          <xsl:attribute name='ref'>
            <xsl:value-of select='$child'/>
          </xsl:attribute>
        </xsl:element>
      </xsl:if>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>
