title: XSLT add node if node does not exist, append child if it does
body: <p>I have the following XML:</p>
  
  <pre><code>&lt;root&gt;
      &lt;book&gt;
          &lt;element2 location="file.txt"/&gt;
          &lt;element3&gt;
              &lt;element3child/&gt;
          &lt;/element3&gt;
      &lt;/book&gt;
      &lt;book&gt;
          &lt;element2 location="difffile.txt"/&gt;
      &lt;/book&gt;
  &lt;/root&gt;
  </code></pre>
  
  <p>I need to be able to copy everything but check if we are in /root/book/element2[@location='whateverfile'] . If we are here we need to check if the sibling element3 exists, if it does not we add a <code>&lt;element3&gt;</code>. If on the other hand it already exists we need to goto the child elements of it and find <code>last()</code> and append an element of our own say <code>&lt;element3child&gt;</code>.</p>
  
  <p>So far i have come up with the following. But bear in mind i am new to XSLT and need some help with syntax etc.</p>
  
  <pre><code>&lt;xsl:template match="@*|node()"&gt;
      &lt;xsl:copy&gt;
          &lt;xsl:apply-templates select="@*|node()"/&gt;
      &lt;/xsl:copy&gt;
  &lt;/xsl:template&gt;
  &lt;xsl:template match="/root/book/element2[@location='file.txt']/../*/last()"&gt;
      &lt;xsl:copy&gt;
          &lt;xsl:apply-templates select="@*|node()"/&gt;
      &lt;/xsl:copy&gt;
      &lt;element3child/&gt;
  &lt;/xsl:template&gt;
  </code></pre>