Getting exsl:node-set to work in PHP
I have the following PHP code, but it's not working. I don't see any errors, but maybe I'm just blind. I'm running this on PHP 5.3.1.
<?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>test@example.com</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()开发者_JAVA百科;
$xsl_processor->importStyleSheet($xsl_dom);
echo $xsl_processor->transformToXML($xml_dom);
?>
This code should output "Hello world" followed by "test@example.com", but the e-mail portion doesn't appear. Any idea what's wrong?
-Geoffrey Lee
The problem is that the provided XSLT code has a default namespace.
Therefore, the <firstname>
, <lastname>
and <email>
elements are in the xhtml namespace. But email
is referenced without any prefix in:
exsl:node-set($person)/email
XPath considers all unprefixed names to be in "no namespace". It tries to find a child of exsl:node-set($person)
called email
that is in "no namespace" and this is unsuccessful, because its email
child is in the xhtml namespace. Thus no email
node is selected and output.
Solution:
This transformation:
<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>test@example.com</email>
</xsl:variable>
<xsl:text>
</xsl:text>
<xsl:value-of select="exsl:node-set($person)/x:email"/>
<xsl:text>
</xsl:text>
</html>
</xsl:template>
</xsl:stylesheet>
when applied on any XML document (not used), produces the wanted result:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:x="http://www.w3.org/1999/xhtml">
<p>Hello world</p>
test@example.com
</html>
Do note:
The added namespace definition with prefix
x
The changed
select
attribute of<xsl:value-of>
:
exsl:node-set($person)/x:email
精彩评论