XSL在php中改变了DOMXpath->的结果

时间:2011-09-28 11:31:20

标签: php xslt xpath

我有:

$XML = new DOMDocument();
$XML->load('demo.xml');

$xpath = new DOMXpath($XML);
$elements = $xpath->evaluate($_GET["xpath"]);

$XSL = new DOMDocument();
$XSL->load('xml2json.xsl', LIBXML_NOCDATA);

$xslt = new XSLTProcessor();
$xslt->importStylesheet($XSL);

echo $xslt->transformToXML($elements);

我收到以下错误:

( ! ) Warning: XSLTProcessor::transformToXml() [xsltprocessor.transformtoxml]: Invalid Document in C:\wamp\www\content.php on line 18

如何将DOMNodeList转换为DOMDocument以使其工作?

以下是我如何使用它!

function getContent(&$NodeContent="",$nod)
{    $NodList=$nod->childNodes;
    for( $j=0 ;  $j < $NodList->length; $j++ )
    {       $nod2=$NodList->item($j);//Node j
        $nodemane=$nod2->nodeName;
        $nodevalue=$nod2->nodeValue;
        if($nod2->nodeType == XML_TEXT_NODE)
            $NodeContent .=  $nodevalue;
        else
        {     $NodeContent .= "<$nodemane";
           $attAre=$nod2->attributes;
           foreach ($attAre as $value)
              $NodeContent .=" {$value->nodeName}='{$value->nodeValue}'" ;
            $NodeContent .=">";                    
            getContent($NodeContent,$nod2);                    
            $NodeContent .= "</$nodemane>";
        }
    }

}


$XML = new DOMDocument();
$XML->load('demo.xml');

$xpath = new DOMXpath($XML);
$elements = $xpath->query($_GET["xpath"]);

$XSL = new DOMDocument();
$XSL->load('xml2json.xsl', LIBXML_NOCDATA);

$xslt = new XSLTProcessor();
$xslt->importStylesheet($XSL);

$newdoc = new DOMDocument;
$newdoc -> preserveWhiteSpace = false;
$newdoc -> formatOutput = true; 

$elm = $elements->item(0);
getContent($docstring,$elm);
$docstring = '<root>'.$docstring.'</root>';
$docstring = str_replace(array("\r\n", "\r", "\n", "\t"), '', $docstring);
$newdoc -> LoadXML($docstring);
echo $xslt->transformToXML($newdoc);

1 个答案:

答案 0 :(得分:1)

你在做什么

$elements = $xpath->evaluate($_GET["xpath"]);
…
echo $xslt->transformToXML($elements);

return values for DOMXPath::evaluate()

  

如果可能,返回类型化结果或包含与给定XPath表达式匹配的所有节点的DOMNodeList。如果表达式格式错误或contextnode无效,DOMXPath::evaluate()将返回FALSE

method signature for transformToXML()

string XSLTProcessor::transformToXML ( DOMDocument $doc )

换句话说,您没有传递DOMDocument并收到“无效文档”错误。