title: How to use xslt to in a hierarchy which a parent <element> may have child <element> which requires different logic
body: <p>So I'm working with an xml document with a structure similar to this</p>
  
  <p>Original XML:</p>
  
  <p><strong>Normal element</strong></p>
  
  <pre><code>&lt;element name="Name1"&gt;
    &lt;document&gt;
      &lt;number&gt;A1&lt;/number&gt;
      &lt;reference&gt;B1&lt;/reference&gt;
    &lt;/document&gt;
  &lt;/element&gt;
  </code></pre>
  
  <p><strong>Element which resembles a grouping</strong>
  (Added root element for clarity)</p>
  
  <pre><code>&lt;root&gt;
  &lt;element name="Name2.Group" id="Name2.xxx.Group"&gt;
     &lt;element name="Name3"&gt;
      &lt;document&gt;
        &lt;number&gt;A2&lt;/number&gt;
        &lt;reference&gt;B2&lt;/reference&gt;
      &lt;/document&gt;
    &lt;/element&gt;
    &lt;element name="Name4"&gt;
      &lt;document&gt;
        &lt;number&gt;A3&lt;/number&gt;
        &lt;reference&gt;B3&lt;/reference&gt;
      &lt;/document&gt;
    &lt;/element&gt;
  &lt;/element&gt;
  &lt;/root&gt;
  </code></pre>
  
  <p>What I am trying to get out of this document is something like this</p>
  
  <pre><code>&lt;references&gt;
    &lt;reference&gt;
      &lt;original&gt;A1&lt;/original&gt;
      &lt;mapping&gt;B1&lt;/mapping&gt;
    &lt;/reference&gt;
   &lt;reference&gt;
    &lt;group id="Name2.xxx.Group"&gt;
      &lt;reference&gt;
          &lt;original&gt;A2&lt;/original&gt;
          &lt;mapping&gt;B2&lt;/mapping&gt;
        &lt;/reference&gt;
        &lt;reference&gt;
          &lt;original&gt;A3&lt;/original&gt;
          &lt;mapping&gt;B3&lt;/mapping&gt;
        &lt;/reference&gt;
      &lt;/group&gt;
    &lt;/reference&gt;
  &lt;/references&gt;
  </code></pre>
  
  <p>I am having trouble coming up with a nice way to do this since matching on element seems to match all elements.</p>
  
  <p>So far I have this, but realized it will not work due to parent and child having the same name for an element, but each needing some different logic</p>
  
  <pre><code>&lt;xsl:template match="/"&gt;
      &lt;xsl:element name="references"&gt;
          &lt;xsl:apply-templates select="@*|node()"/&gt;
      &lt;/xsl:element&gt;
  &lt;/xsl:template&gt;
  &lt;xsl:template match="element"&gt;
      &lt;xsl:element name="reference"&gt;
          &lt;xsl:if test="element/document"&gt;
              &lt;xsl:element name="original"&gt;
                  &lt;xsl:value-of select="element/document/number"/&gt;
              &lt;/xsl:element&gt;
              &lt;xsl:element name="mapping"&gt;
                  &lt;xsl:value-of select="element/document/reference"/&gt;
              &lt;/xsl:element&gt;
              &lt;xsl:element name="id"&gt;
                  &lt;xsl:value-of select="@id"/&gt;
              &lt;/xsl:element&gt;
          &lt;/xsl:if&gt;
      &lt;/xsl:element&gt;
  &lt;/xsl:template&gt;
  </code></pre>