title: How to sort XML nodes by ID values using XSLT?
body: <p>I have a large xml file with a lot of row nodes. I want to sort it by each row's id value.</p>
  
  <p>So this would be an example input:</p>
  
  <pre><code>&lt;database&gt;
    &lt;table&gt;
      &lt;row&gt;
        &lt;id&gt;10&lt;/id&gt;
        &lt;foo&gt;bar&lt;/foo&gt;
      &lt;/row&gt;
      &lt;row&gt;
        &lt;id&gt;5&lt;/id&gt;
        &lt;foo&gt;poit&lt;/foo&gt;
      &lt;/row&gt;
      &lt;row&gt;
        &lt;id&gt;1&lt;/id&gt;
        &lt;foo&gt;narf&lt;/foo&gt;
      &lt;/row&gt;
    &lt;/table&gt;
  &lt;/database&gt;
  </code></pre>
  
  <p>and this the expected output:</p>
  
  <pre><code>&lt;database&gt;
    &lt;table&gt;
      &lt;row&gt;
        &lt;id&gt;1&lt;/id&gt;
        &lt;foo&gt;narf&lt;/foo&gt;
      &lt;/row&gt;
      &lt;row&gt;
        &lt;id&gt;5&lt;/id&gt;
        &lt;foo&gt;poit&lt;/foo&gt;
      &lt;/row&gt;
      &lt;row&gt;
        &lt;id&gt;10&lt;/id&gt;
        &lt;foo&gt;bar&lt;/foo&gt;
      &lt;/row&gt;
    &lt;/table&gt;
  &lt;/database&gt;
  </code></pre>
  
  <p>How can I achieve that? I have <code>xmlstarlet</code> at my disposal. It features a <a href="http://xmlstar.sourceforge.net/doc/UG/ch04s02.html" rel="nofollow noreferrer">transform</a> and appearantly I can provide a xslt stylecheet in a xsl file.</p>
  
  <p>I haven't worked with xslt before and am unsure how to proceed.</p>
  
  <p>I have found <a href="https://stackoverflow.com/questions/19829322/sort-nodes-in-xml-using-xslt">some related sorting questions</a> providing some XSLT examples, yet I could not get them working in my use case.</p>
  
  <p>My current <code>sort.xslt</code> (Note: I don't know what I am doing) looks like:</p>
  
  <pre><code>&lt;xsl:stylesheet version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
   &lt;xsl:output omit-xml-declaration="yes" indent="yes"/&gt;
   &lt;xsl:strip-space elements="*"/&gt;
   &lt;xsl:template match="node()|@*"&gt;
    &lt;xsl:copy&gt;
     &lt;xsl:apply-templates select="@*"&gt;
      &lt;xsl:sort select="row()"/&gt;
     &lt;/xsl:apply-templates&gt;
     &lt;xsl:apply-templates select="node()"&gt;
      &lt;xsl:sort select="id()"/&gt;
     &lt;/xsl:apply-templates&gt;
    &lt;/xsl:copy&gt;
   &lt;/xsl:template&gt;
  &lt;/xsl:stylesheet&gt;
  </code></pre>
  
  <p>Yet it fails:</p>
  
  <pre><code>$ xmlstarlet tr sort.xsl example.xml 
  Invalid number of arguments
  xmlXPathCompiledEval: evaluation failed
  Invalid number of arguments
  xmlXPathCompiledEval: evaluation failed
  Invalid number of arguments
  xmlXPathCompiledEval: evaluation failed
  &lt;database&gt;
    &lt;table/&gt;
  &lt;/database&gt;
  </code></pre>