Splitting XML into multiple files with XSLT

Responding to your comment on @Dimitre’s answer…

You wrote,

<xsl:template match="https://stackoverflow.com/">
  <xsl:for-each select="elem/file">
    <xsl:result-document method="xml" href="https://stackoverflow.com/questions/4036233/file_{@id}-output.xml">
      <xsl:copy-of select="."/>
    </xsl:result-document>
  </xsl:for-each>
</xsl:template> 

This doesn’t quite match your XML, which has rootelem as an outermost element, and your comment says root as an outermost element. You probably want something like this:

<xsl:template match="/root">
  <xsl:for-each select="elem/file">
    <xsl:result-document method="xml" href="https://stackoverflow.com/questions/4036233/file_{@id}-output.xml">
      <root>
        <xsl:copy-of select="/root/@*" />
        <elem>
          <xsl:copy-of select="../@* | ." />
        </elem>
      </root>
    </xsl:result-document>
  </xsl:for-each>
</xsl:template> 

You could get fancier, trying to use <xsl:copy> instead of literal result elements for root and elem, but it doesn’t seem worth the effort unless they’re going to vary.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)