XSLT:将标记的所有属性传递给php函数

时间:2011-10-06 18:14:14

标签: php xslt

我编写了以下XSLT模板:

<xsl:template match="foo:*">
    <xsl:processing-instruction name="php">$s = ob_get_clean(); ob_start(); $this->callExtensionStartHandler('<xsl:value-of select="local-name()" />');</xsl:processing-instruction>
    <xsl:apply-templates/>
    <xsl:processing-instruction name="php">$sExtensionContent = ob_get_clean(); ob_start(); echo $s; echo $this->callExtensionEndHandler('<xsl:value-of select="local-name()" />', $sExtensionContent);</xsl:processing-instruction>
</xsl:template>

现在我想将标记的所有属性及其值传递给php函数。如果我有一个模板:

<foo:test id="a" bar="xzz"/>

我想在我的php函数中有一个数组('id'=&gt;'a','bar'=&gt;'xzz')。那可能吗。我不想限制属性的名称,因此可以有任何属性名称。

2 个答案:

答案 0 :(得分:1)

你不能只传递元素本身然后用适当的PHP函数获取所有属性吗?这样你就不需要关心属性的名称,因为我确信有一种方法可以迭代php中元素的所有属性:)

答案 1 :(得分:1)

我不熟悉PHP,但这可能会有所帮助:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:foo="foo:foo">
 <xsl:output method="text"/>

 <xsl:template match="foo:test">
  array(<xsl:apply-templates select="@*"/>)
 </xsl:template>

 <xsl:template match="foo:test/@*">
  <xsl:if test="not(position()=1)">, </xsl:if>
  <xsl:value-of select=
  'concat(&quot;&apos;&quot;,name(),&quot;&apos;&quot;,
          " => ",
          &quot;&apos;&quot;,.,&quot;&apos;&quot;)'/>
 </xsl:template>
</xsl:stylesheet>

对此XML文档应用此转换时(提供的转换,格式正确):

<foo:test id="a" bar="xzz" xmlns:foo="foo:foo"/>

产生了想要的正确结果

  array('id' => 'a', 'bar' => 'xzz')

更新:OP在评论中询问:

  

谢谢,看起来很棒!是否可以添加一个转义到   属性值?每个'应该成为'

回答:是的,我们可以通过略微修改原始解决方案来获得此输出:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:foo="foo:foo">
 <xsl:output method="text"/>

 <xsl:template match="foo:test">
  array(<xsl:apply-templates select="@*"/>)
 </xsl:template>

 <xsl:template match="foo:test/@*">
  <xsl:if test="not(position()=1)">, </xsl:if>
  <xsl:value-of select=
  'concat(&quot;\&quot;,&quot;&apos;&quot;,name(),&quot;\&quot;,&quot;&apos;&quot;,
          " => ",
          &quot;\&quot;,&quot;&apos;&quot;,.,&quot;\&quot;,&quot;&apos;&quot;)'/>
 </xsl:template>
</xsl:stylesheet>

当应用于同一XML文档时,此转换会生成

  array(\'id\' => \'a\', \'bar\' => \'xzz\')
相关问题