开发者

Need to extract Sub-Tree of XML, before processing with XSLT Processor

I'm processing a XML with XSL with PHP to a HTML output. So far, so good. Here's my code.

<?php

$xslDoc = new DOMDocument();
$xslDoc->load("content.xsl");

$xmlDoc = new DOMDocument();
$xmlDoc->load("content.xml");

    // some xpath/dom-query filtering to get 
    // subtree of loaded xml-file

$proc = new XSLTProcessor();
$proc->importStylesheet($xslDoc);
ech开发者_如何转开发o $proc->transformToXML($xmlDoc);

?>  

Like you can see, this is a simple XSLT Processor. The output works well. For example I have in the given XML three sibling nodes "node":

<root>
 <node>
  <subnode>..</subnode>
 </node>
 <node>
  <subnode>..</subnode>
 </node>
 <node>
  <subnode>..</subnode>
 </node>
</root>

Now I want just pass the second node through the XML Processor.

How can I do this?

chris


According to http://www.php.net/manual/en/xsltprocessor.transformtodoc.php, the transformToDoc method takes any DOM node as its argument so you could access $xmlDoc->getElementsByTagName('node')->item(1) and pass that to transformToDoc and then use saveXML or saveHTML to get a string of XML or HTML, depending on what kind of result you are looking for.


I solved my task by my own - but thank you for your application.

Here is my code:

$xmlDoc = new DOMDocument();
$xmlDoc->preserveWhiteSpace = false;
$xmlDoc->load("content.xml");

$xpath = new DOMXPath($xmlDoc);
$query = '//ContentData/Content[1]/Headline';
$nodeList = $xpath->query($query);


$newDom = new DOMDocument('1.0','UTF-8');
$root = $newDom->createElement('root');
$root = $newDom->appendChild($root);


foreach ($nodeList as $domElement){
   $domNode = $newDom->importNode($domElement, true);
   $root->appendChild($domNode);
}

$newDom->saveXML();


$xslDoc = new DOMDocument();
$xslDoc->load("content.xsl");

$proc = new XSLTProcessor();
$proc->importStylesheet($xslDoc);

echo $proc->transformToXML($newDom);    
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜