Pergunta

Estou tentando incluir arquivos de origem diferentes (e.g.file1.xml e file2.xml) e ter esses inclui resolvido por uma transformação XSLT usando PHPs XSLTProcessor.Esta é a minha entrada:

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>

transformação.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"));
?>

A minha saída desejada

<?xml version="1.0" encoding="utf-8" ?>
<root>
    <!-- transformed contents of file1.xml -->
    <!-- transformed contents of file2.xml -->
</root>

Minha corrente de saída é uma cópia exata do meu arquivo de origem:

<?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>
Foi útil?

Solução

Ele saiu, eu só esqueceu de um simples, mas importante linha do meu código PHP.Eu tinha que ligar para DOMDocument::xinclude para ter o inclui resolvidos antes que a transformação é feita.

O exemplo completo:

<?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"));
?>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top