How do I pass an XPath expression as an XSL param

2019-07-21 21:40发布

问题:

I have a very large XML file that I'm extracting information from, and transforming it into a different XML format. I have the transformation itself running perfectly, so now I would like to make it more flexible by using PHP to pass in a variable select="" criteria.

The following is the working XSLT code I'm using (truncated for simplicity):

<xsl:param name="criteria" select="//Product[PublicationDate &gt; 20141231]" />
<xsl:template match="ONIXMessage">
 <xsl:for-each select="$criteria">
  <xsl:apply-templates select="Title"/>
 </xsl:for-each>
</xsl:template>

The value of $criteria is an XPath expression, and the above works without trouble. The issue is when I try to use PHP to pass a different value into $criteria:

$proc = new XSLTProcessor;
$proc->importStyleSheet( $icml );
$proc->setParameter( "", "criteria", "//Product[Imprint = 'Nightwood']");

The transformation fails entirely when I use setParameter. I know the expressions themselves are accurate because the transfrom works fine when I enter them directly into the XSLT (without PHP).

From what I understand, the problem is that the parameter is being passed as a string rather than as a proper XPath expression, and so the XSLT cannot resolve select="" to a node-set. So how do I prevent that? It's important to pass a whole XPath expression so that I can change the for-each criteria to whatever I want.

回答1:

From what I understand, the problem is that the parameter is being passed as a string rather than as a proper XPath expression

That is a correct assessment. You need a processor that can evaluate the string as an XPath expression. Fortunately for you, the libxslt processor used by PHP does support the EXSLT dyn:evaluate() extension function.

Without this, you would have to pass the parameter to another XSLT stylesheet, whose function would be to generate the XSLT styleshhet required for the actual transform.



标签: php xml xslt xpath