Using XSLT as an XML pre-processor

不羁的心 提交于 2019-12-02 02:29:34

I've worked out how to do it as below, but some parts such as the "contents" variable didn't seem like the best way to handle this.

Well, basically you got it right. You can still improve it a little, though:

<xsl:variable name="defines" select="document($defines-uri)/defines"/>

<xsl:template match="ifdef">
  <xsl:variable name="this" select="."/>

  <xsl:for-each select="$defines[def = $this/@select]">
    <xsl:apply-templates select="$this/node()" />
  </xsl:for-each>
</xsl:template>

The <xsl:for-each> changes the context node. Within it, the . refers to the node being iterated over, not the one that had been matched by the <xsl:template>.

That means you have to preseve the "outer" context in a variable, this is standard practice.

You're doing really well for someone who's only just beginning with XSLT and XML.

This isn't an answer to your question, but I just wanted to say that this might be a safer "copy by default" template:

<xsl:template match="node() | @*">
    <xsl:copy><xsl:apply-templates select="node() | @*"/></xsl:copy>
</xsl:template>

Yours works by grace of a certain default built-in template. But you might get strange behaviour regarding text nodes (or other things that aren't elements) when you add more templates, since the default has a low priority.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!