我写了一个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和其他选项。如果它很容易改变,让我在看到它的时候快速看到内容,那么我就可以使用一些小设置。这不是一个大问题,但似乎有一些确定的空间可以帮助减少这些烦人的任务之一。 –