1

我正在尝试对注释进行模板匹配,以便它查找虚拟包含并将其转换为 php 包含:

<node>
<!--#include virtual="/abc/contacts.html" -->
<!-- some random comment -->
</node>

<node>
<?php include($_SERVER[DOCUMENT_ROOT]."/abc/contacts.html"); ?>
<!-- some random comment -->
</node>

我正在尝试做类似的事情:

<xsl:template match="comment()" >
<xsl:analyze-string select="." regex="^[\s\S]*&lt;!">
<xsl:matching-substring>
<xsl:text disable-output-escaping="yes">&lt;?php&nbsp;</xsl:text> <xsl:value-of select="." /> <xsl:text disable-output-escaping="yes">&nbsp;?&gt;</xsl:text>
</xsl:matching-substring>
</xsl:analyze-string>
</xsl:template>

非常感谢解决此问题的任何帮助。

4

1 回答 1

1

为此,您不需要 XSLT 2.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

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

 <xsl:template match=
  "comment()[starts-with(normalize-space(),'#include virtual=')]">

  <xsl:processing-instruction name="php">
   <xsl:text>include($_SERVER[DOCUMENT_ROOT].</xsl:text>
   <xsl:value-of select=
   "substring-after(normalize-space(),'#include virtual=')"/>
   <xsl:text>);</xsl:text>
  </xsl:processing-instruction>
 </xsl:template>
</xsl:stylesheet>

当此转换应用于提供的 XML 文档时:

<node>
    <!--#include virtual="/abc/contacts.html" -->
    <!-- some random comment -->
</node>

产生了想要的正确结果:

<node>
    <?php include($_SERVER[DOCUMENT_ROOT]."/abc/contacts.html");?>
    <!-- some random comment -->

</node>

说明

正确使用标识规则、模板匹配模式、XPath 函数和normalize-space()XSLT指令。starts-with()xsl:processing-instruction

于 2013-01-12T04:25:58.477 回答