我正在尝试包含不同的源文件(例如文件1。xml和file2。xml),并有这些包括解析使用Php的XSLT转换 XSLTProcessor.这是我的输入:

来源。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>

变换。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>

变换。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>
有帮助吗?

解决方案

事实证明,我只是在我的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"));
?>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top