title: Can I use XSLT to parse XML into sub-files? (+ Alternative Languages/Methods)
body: <p>Hey all, I have highly repetitive data with a depth of 5 nodes deep (including the root) that needs to be broken apart. (I'll include a fast sample in a minute.) What I'm looking to do is parse a ~5mb XML file into smaller sub-files based on the 3rd-depth nodes. But after that, it gets more complicated.</p>
  
  <p>The task's requirements are these:</p>
  
  <ol>
  <li>Sub-files must maintain the hierarchical parents of the 3rd level node which is extracted, including their attributes.</li>
  <li>Sub-files must retain all attributes and children nodes.</li>
  <li>If XSLT cannot handle the job, attempt it in Ruby. <em>If you aren't good at XSLT, but can tell me how to do it in Ruby or even Python, please feel free to contribute an answer in those languages.</em> (Else try and stick with XSLT or pseudo-code.)</li>
  </ol>
  
  <p>DOM Hierarchy:</p>
  
  <pre><code>&lt;xml attr="whatever"&gt;
    &lt;major-group name="whatever"&gt;
      &lt;minor-group name="whatever"&gt;
        &lt;another-group name="whatever"&gt;
          &lt;last-node name="whatever"&gt;&lt;/last-node&gt;
        &lt;/another-group&gt;
      &lt;/minor-group&gt;
    &lt;/major-group&gt;
  &lt;/xml&gt;
  </code></pre>
  
  <p>Which I need to split on the <strong>minor-group</strong> element while retaining both its children and direct parents, and put all that (for each minor-group) in an external file. I have several files to split in this manner.</p>
  
  <p>And... having never before parsed XML in Ruby, and having just begun using XSLT, I cannot yet write a script to accomplish my task with either.</p>
  
  <p>I'm curious to see if XSLT is up to the task.  <code>:&gt;</code></p>
  
  <p><strong>Edit:</strong></p>
  
  <p>Here's my resulting code, with the ability to show a stylesheet at the beginning of the file.</p>
  
  <pre><code>&lt;?xml version="1.0"?&gt;
  &lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"&gt;
    &lt;xsl:output method="xml"/&gt;
    &lt;xsl:template match="minor-group"&gt;
      &lt;xsl:variable name="filename"&gt;&lt;xsl:value-of select="concat(@name,'.xml')"/&gt;&lt;/xsl:variable&gt;
      &lt;xsl:result-document href="{$filename}"&gt;
        &lt;xsl:text disable-output-escaping="yes"&gt;
          &lt;![CDATA[&lt;?xml-stylesheet type="text/xsl" href="../web.xslt"?&gt;]]&gt;
        &lt;/xsl:text&gt; 
        &lt;xml&gt;
          &lt;xsl:attribute name="whatever"&gt;&lt;xsl:value-of select="../../@whatever" /&gt;&lt;/xsl:attribute&gt;
          &lt;major-group&gt;
            &lt;xsl:attribute name="whatever"&gt;&lt;xsl:value-of select="../@whatever" /&gt;&lt;/xsl:attribute&gt;
            &lt;xsl:copy-of select="."/&gt;
          &lt;/major-group&gt;
        &lt;/xml&gt;
      &lt;/xsl:result-document&gt;
    &lt;/xsl:template&gt;
  &lt;/xsl:stylesheet&gt;
  </code></pre>