我寫了一個PHP文件在我的localhost web服務器上運行。這是一個僅需要更改一個變量的模板,以識別要轉換的XML文件的路徑。當它被調用時,它會通過插入適當的樣式表處理指令來傳遞該XML。
我喜歡這種方法的事情是:
- 建立新的轉換測試是快速和容易。只需複製php文件,重命名它並在必要時將路徑更改爲XML。
- 測試更新的XML數據非常簡單。與具有源XML文檔的多個副本相比,此方法使用單個文件。當對它進行更新時,會在每次轉換中看到它們。
- 使用熱鍵可以非常快速地檢查更改。一個快速的Cmd + S,Cmd + Tab,Cmd + R將樣式表保存在編輯器中,跳轉到瀏覽器並重新加載速度非常快,但幾乎不引人注意。
- 由於XML文檔的路徑是在代碼中定義的,我可以在需要時使用它中的變量。例如,傳遞一個唯一的ID來提取名稱中相應值的文件。
- 沒有其他軟件可以安裝,因爲我的機器已經有了Apache並且運行了php。
的PHP文件中的模板代碼爲:
<?php
// Set the path to the XML file you want to use.
$xmlPath = "example.xml";
////////////////////////////////////////////////////////////////////////////////
// You shouldn't have be mess with any of this.
// Let the browser know XML is on the way.
header('Content-type: text/xml');
// get the basename of the current file
$fileBaseName = basename($_SERVER["SCRIPT_NAME"], ".php");
// setup the stylesheet to use
$xsltStylesheet = sprintf('<?xml-stylesheet type="text/xsl" href="%s.xsl"?>', $fileBaseName);
// pull in the contents of the source XML file.
$xmlData = file_get_contents($xmlPath);
// split the file data looking for processing instructions
$splitArray = explode("?>", $xmlData);
// Pop the main data off the end of the array
$mainData = array_pop($splitArray);
// If there were no headers, push a default onto the split array
if(count($splitArray) == 0) {
array_push($splitArray, '<?xml version="1.0" encoding="UTF-8"?>');
array_push($splitArray, $xsltStylesheet);
}
// otherwise check the headers to see if there is already a stylesheet
else {
// set a flag to watch for a stylesheet
$hasStylesheet = 0;
// loop thru the headers
foreach ($splitArray as &$splitItem) {
// add the closing string back in.
$splitItem .= '?>';
// See if it's a stylesheet call
if(strrpos($splitItem, '<?xml-stylesheet')) {
// update the flag to show you hit a stylesheet
$hasStylesheet = 1;
// change the href call for the style sheet.
$splitItem = preg_replace('/\shref="[^"]*"/', ' href="' . $fileBaseName . '.xsl"', $splitItem);
}
}
// If you didn't find a stylesheet instruction, add it.
if(!$hasStylesheet) {
array_push($splitArray, $xsltStylesheet);
}
}
// reassemble the data
$mainData = implode("\n", $splitArray) . $mainData;
echo $mainData;
要使用它,
- 的目錄中是通過Web服務器訪問創建樣式表。
- 使用與樣式表相同的基本文件名在同一目錄中複製PHP代碼。例如,如果樣式表是「test-example.xsl」,那麼php文件將是「test-example.php」。
- 更新php文件中的「$ xmlPath」變量以指向用於測試的XML。
- 通過網絡瀏覽器打開php頁面(例如http://localhost/test-example.php)並查看轉換結果。
在當前狀態下,此代碼應該非常健壯。它會將樣式表調用添加到尚未擁有它們的XML文件中,並將樣式表調用更改爲具有這些樣式的調用。和其他任何東西一樣,它可以被構建得更多,但它涵蓋了我現在需要的東西。
謝謝@LarsH,我會檢查出您在第二項中提到的oXygen和其他選項。如果它很容易改變,讓我在看到它的時候快速看到內容,那麼我就可以使用一些小設置。這不是一個大問題,但似乎有一些確定的空間可以幫助減少這些煩人的任務之一。 –