开发者

XSL tansform result of DOMXpath->evaluate in php

I have:

$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);

I get the following error:

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

How do I convert a DOMNodeList to a DOMDocument to make this work?

Here is how I got it to work!

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 = '<开发者_StackOverflowroot>'.$docstring.'</root>';
$docstring = str_replace(array("\r\n", "\r", "\n", "\t"), '', $docstring);
$newdoc -> LoadXML($docstring);
echo $xslt->transformToXML($newdoc);


You are doing

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

The return values for DOMXPath::evaluate() are

Returns a typed result if possible or a DOMNodeList containing all nodes matching the given XPath expression. If the expression is malformed or the contextnode is invalid, DOMXPath::evaluate() returns FALSE.

The method signature for transformToXML() states

string XSLTProcessor::transformToXML ( DOMDocument $doc )

In other words, you are not passing a DOMDocument and get an "Invalid Document" error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜