2012-11-25 19 views
2

好吧,這讓我感到非常緊張。我正在嘗試使用XML文件和一些PHP來製作一個簡單的CMS。我有一個這樣的XML文件:對使用​​DOMXPath選擇的XML文檔的一部分執行XSLT轉換

<?xml version="1.0" encoding="utf-8"?> 
<sections> 
<section name="about"> 
    <maintext> 
     <p>Here is some maintext. </p> 
    </maintext> 
</section> 
<section name="james"> 
    <maintext> 
     <p>Zippidy do.</p> 
    </maintext> 
</section> 
</sections> 

然後就是XSL文件:

<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
<xsl:output method="html" /> 
<xsl:template match="/"> 
<xsl:apply-templates /> 
</xsl:template> 
<xsl:template match="section"> 
<div class="section"> 
    <xsl:apply-templates /> 
</div> 
</xsl:template> 
<xsl:template match="maintext"> 
<xsl:copy-of select="child::node()" /> 
</xsl:template> 
</xsl:stylesheet> 

這種轉變工作正常 - 我得到幾個簡單的段落:

<p>Here is some maintext. </p>  
<p>Zippidy do.</p> 

然而,我現在有一個應該查詢XML的PHP​​文件,根據其GET參數採取特定的「部分」。然後在XML的那部分上運行轉換,並回應結果。

<?php 

$sectionName = $_GET["section"]; 
$content = new DOMDocument(); 
$content->load("content.xml"); 
$transformation = new DOMDocument(); 
$transformation->load("transform-content.xsl"); 
$processor = new XSLTProcessor(); 
$processor->importStyleSheet($transformation); 
$xpath = new DOMXPath($content); 
$sectionXML = $xpath->query("section[@name='".$sectionName."']")->item(0); 

echo $processor->transformToXML($sectionXML); 
?> 

問題是,無論我做什麼整個XML文件轉換,而不僅僅是我選擇的部分與查詢。我在這裏做錯了什麼?!

+0

'transformToXML'需要'DOMDocument'參數,而不是任意節點。如果您使用'transformToDoc',它會起作用嗎? –

+0

否則,創建一個新的空白文檔,[import](http://www.php.net/manual/en/domdocument.importnode.php)和[append](http://www.php.net/手動/ en/domnode.appendchild.php)的section元素,然後轉換它。 –

+0

TransforToDoc無法正常工作,但使用導入和附加方法完美工作 - 感謝您的幫助!這很奇怪,雖然在我的原始代碼中,transformToXML繼續前進,並在剛剛從路徑查詢中獲取節點時轉換原始XML文檔。爲什麼不只是因爲錯誤的類型而拋出錯誤?哦,好吧......無論如何都解決了問題! :) –

回答

1

transformToXML需要DOMDocument,而不僅僅是任何節點。我猜你現在的代碼在做什麼,正在轉變你傳遞它的節點的「所有者文檔」。

嘗試創建一個新文檔,然後使用$newDoc->appendChild($newDoc->importNode($sectionXML, true))將現有元素附加到新文檔,然後轉換此文檔而不是原始文檔。