2010-06-01 53 views
9

我有以下PHP代码,但它不起作用。我没有看到任何错误,但也许我只是失明。我在PHP 5.3.1上运行这个。获取exsl:node-set在PHP中工作

<?php 
$xsl_string = <<<HEREDOC 
<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet version="1.0" 
       xmlns="http://www.w3.org/1999/xhtml" 
       xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
       xmlns:exsl="http://exslt.org/common" 
       extension-element-prefixes="exsl"> 
    <xsl:template match="/"> 
    <p>Hello world</p> 
    <xsl:variable name="person"> 
     <firstname>Foo</firstname> 
     <lastname>Bar</lastname> 
     <email>[email protected]</email> 
    </xsl:variable> 
    <xsl:value-of select="exsl:node-set(\$person)/email"/> 
    </xsl:template> 
</xsl:stylesheet> 
HEREDOC; 

$xml_dom = new DOMDocument("1.0", "utf-8"); 
$xml_dom->appendChild($xml_dom->createElement("dummy")); 

$xsl_dom = new DOMDocument(); 
$xsl_dom->loadXML($xsl_string); 

$xsl_processor = new XSLTProcessor(); 
$xsl_processor->importStyleSheet($xsl_dom); 
echo $xsl_processor->transformToXML($xml_dom); 
?> 

此代码应该输出“Hello world”后跟“[email protected]”,但电子邮件部分不会显示。任何想法有什么不对?

-Geoffrey李

+0

很好的问题(+1)。请参阅我的答案以获得解释和完整解决方案。 – 2010-06-01 13:07:42

回答

8

的问题是,所提供的XSLT代码有一个默认的命名空间。

因此,<firstname>,<lastname><email>元素位于xhtml命名空间中。但email是没有任何前缀的引用:

exsl:node-set($person)/email 

的XPath考虑所有前缀的名字是在“没有命名空间”。它试图找到名为emailexsl:node-set($person)的孩子,该孩子处于“no namespace”,并且这是不成功的,因为其email孩子位于xhtml命名空间中。因此没有选择并输出email节点。

解决方案

这种转变:

<xsl:stylesheet version="1.0" 
    xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:x="http://www.w3.org/1999/xhtml" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:exsl="http://exslt.org/common" 
    exclude-result-prefixes="exsl x"> 
    <xsl:output omit-xml-declaration="yes" indent="yes"/> 

    <xsl:template match="/"> 
    <html> 
    <p>Hello world</p> 
    <xsl:variable name="person"> 
     <firstname>Foo</firstname> 
     <lastname>Bar</lastname> 
     <email>[email protected]</email> 
    </xsl:variable> 
    <xsl:text>&#xA;</xsl:text> 
    <xsl:value-of select="exsl:node-set($person)/x:email"/> 
    <xsl:text>&#xA;</xsl:text> 
    </html> 
    </xsl:template> 
</xsl:stylesheet> 

当任何XML文档(未使用)应用时产生通缉的结果

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:x="http://www.w3.org/1999/xhtml"> 
    <p>Hello world</p> 
[email protected] 
</html> 

待办事项

  1. 前缀x

  2. <xsl:value-of>的改变select属性添加的命名空间定义:

exsl:node-set($person)/x:email

+0

啊,现在完全有意义。谢谢你的答案! – geofflee 2010-06-01 13:44:53