2011-06-20 49 views
1

我有一个XML文档,我试图用xpath查询,然后通过XSLTProcessor运行生成的节点。 xpath查询工作正常,但我无法弄清楚如何在XSLTProcessor中使用SimpleXMLElement。任何帮助,将不胜感激。SimpleXML Xpath查询和transformToXML

$data = simplexml_load_file('document.xml'); 
$xml = $data->xpath('/nodes/node[1]'); 
$processor = new XSLTProcessor; 
$xsl = simplexml_load_file('template.xsl'); 
$processor->importStyleSheet($xsl); 
echo '<div>'.$processor->transformToXML($xml).'</div>'; 

XML:

<nodes> 
    <node id="5"> 
     <title>Title</title> 
    </node> 
</nodes> 

XSL:

<?xml version="1.0"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

<xsl:template match="//node"> 
<xsl:value-of select="@id" /> 
<xsl:value-of select="title" /> 
... 

回答

0

我认为你不能传递$xmlXSLTProcessor::transformToXML方法,因为它的阵列(由SimpleXMLElement::xpath生产):

PHP警告: XSLTProcessor中:: transformToXml() 预计参数1为对象, 阵列中/var/www/index.php给定上 线11

简单的补救办法是只是把XPath表达式成XSL样式表:

<xsl:output method="html"/> <!-- don't embed XML declaration --> 

<xsl:template match="/nodes/node[1]"> 
    <xsl:value-of select="@id"/> 
    <xsl:value-of select="title"/> 
</xsl:template> 

和:

$xml = simplexml_load_file('document.xml'); 
$xsl = simplexml_load_file('template.xsl'); 

$xslt = new XSLTProcessor; 
$xslt->importStyleSheet($xsl); 

echo '<div>'.$xslt->transformToXML($xml).'</div>'; 

编辑:

另一种方法是只使用XSL数组的第一个元素变换(确保它不为空):

$data = simplexml_load_file('document.xml'); 
$xpath = $data->xpath('/nodes/node[1]'); 
$xml = $xpath[0]; 

$xsl = simplexml_load_file('template.xsl'); 

$xslt = new XSLTProcessor; 
$xslt->importStyleSheet($xsl); 

echo '<div>'.$xslt->transformToXML($xml).'</div>'; 

和:

<xsl:template match="node"> 
    <xsl:value-of select="@id"/> 
    <xsl:value-of select="title"/> 
</xsl:template> 
+0

谢谢,但XSL样式表将被使用在不同的背景下,所以它需要比这更抽象。 – bjudson

+0

@handsofaten:好的,看我更新的答案。 –

+0

这有助于,谢谢。我也只是注意到这里的例子1,这很有用:http://php.net/manual/en/simplexmlelement.xpath.php – bjudson