我试图包含不同的源文件(例如file1.xml和file2.xml),并将这些文件解析为使用PHP XSLTProcessor进行XSLT转换。这是我的意见:
source.xml
<?xml version="1.0" encoding="utf-8" ?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="file1.xml" />
<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="file2.xml" />
</root>transform.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xi="http://www.w3.org/2001/XInclude">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
</xsl:transform>transform.php
<?php
function transform($xml, $xsl) {
global $debug;
// XSLT Stylesheet laden
$xslDom = new DOMDocument("1.0", "utf-8");
$xslDom->load($xsl, LIBXML_XINCLUDE);
// XML laden
$xmlDom = new DOMDocument("1.0", "utf-8");
$xmlDom->loadHTML($xml); // loadHTML to handle possibly defective markup
$xsl = new XsltProcessor(); // create XSLT processor
$xsl->importStylesheet($xslDom); // load stylesheet
return $xsl->transformToXML($xmlDom); // transformation returns XML
}
exit(transform("source.xml", "transform.xsl"));
?>我想要的输出是
<?xml version="1.0" encoding="utf-8" ?>
<root>
<!-- transformed contents of file1.xml -->
<!-- transformed contents of file2.xml -->
</root>我的当前输出是源文件的精确副本:
<?xml version="1.0" encoding="utf-8" ?>
<root>
<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="file1.xml" />
<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="file2.xml" />
</root>发布于 2012-10-01 13:30:39
结果,我忘了PHP代码中一个简单但重要的行。在完成转换之前,我必须调用DOMDocument::xinclude来解析包含。
完整的例子:
<?php
function transform($xml, $xsl) {
global $debug;
// XSLT Stylesheet laden
$xslDom = new DOMDocument("1.0", "utf-8");
$xslDom->load($xsl, LIBXML_XINCLUDE);
// XML laden
$xmlDom = new DOMDocument("1.0", "utf-8");
$xmlDom->load($xml);
$xmlDom->xinclude(); // IMPORTANT!
$xsl = new XsltProcessor();
$xsl->importStylesheet($xslDom);
return $xsl->transformToXML($xmlDom);
}
exit(transform("source.xml", "transform.xsl"));
?>https://stackoverflow.com/questions/12672146
复制相似问题