我有以下PHP代码,但它不工作。我看不到任何错误,但也许我只是看不见。我在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();
$xsl_processor->importStyleSheet($xsl_dom);
echo $xsl_processor->transformToXML($xml_dom);
?>这段代码应该输出"Hello world“,后跟"test@example.com",但是电子邮件部分没有出现。知道出什么问题了吗?
-Geoffrey Lee
发布于 2010-06-01 21:06:55
XSLT的问题在于提供的代码有一个默认的名称空间。
因此,<firstname>、<lastname>和<email>元素位于xhtml名称空间中。但是引用email时没有任何前缀:
exsl:节点集($person)/email
XPath认为所有无前缀的名称都在"no namespace“中。它试图查找位于"no namespace“中的名为email的exsl:node-set($person)的子项,但没有成功,因为它的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>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>在任何XML文档(未使用)上应用时,都会生成所需的结果
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:x="http://www.w3.org/1999/xhtml">
<p>Hello world</p>
test@example.com
</html>注意到
使用前缀x
select attribute of <xsl:value-of>:更改添加的命名空间定义
exsl:node-set($person)/x:email
https://stackoverflow.com/questions/2949836
复制相似问题