Apply transforms to XML attribute containing escaped HTML

后端 未结 2 393
春和景丽
春和景丽 2021-01-27 16:07

I have some XML that looks like this:



    

        
相关标签:
2条回答
  • 2021-01-27 16:46

    Here's one way you could do it, by calling into a PHP function from XSLT:

    function parseHTMLString($html)
    {
        $doc = new DOMDocument();
        $doc->loadHTML($html);
        return $doc;
    }
    
    $xml = <<<EOB
    <root>
        <issue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <comment text="&lt;div class=&quot;wiki text&quot;&gt;&lt;h4&gt;Tom Fenech&lt;/h4&gt;Here is a comment&lt;/div&gt;&#10;"/>
        </issue>
    </root>
    EOB;
    
    $xsl = <<<EOB
    <xsl:stylesheet version="1.0"
         xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
         xmlns:php="http://php.net/xsl"
         xsl:extension-element-prefixes="php">
    <xsl:output method="html" encoding="utf-8" indent="yes"/>
     <xsl:template match="comment">
       <xsl:apply-templates select="php:functionString('parseHTMLString', @text)//div/h4"/>
     </xsl:template>
    
     <xsl:template match="div/h4">
       <h2><xsl:apply-templates/></h2>
     </xsl:template>
    </xsl:stylesheet>
    EOB;
    
    $xmldoc = new DOMDocument();
    $xmldoc->loadXML($xml);
    
    $xsldoc = new DOMDocument();
    $xsldoc->loadXML($xsl);
    
    $proc = new XSLTProcessor();
    $proc->registerPHPFunctions('parseHTMLString');
    $proc->importStyleSheet($xsldoc);
    echo $proc->transformToXML($xmldoc);
    
    0 讨论(0)
  • 2021-01-27 17:04

    You cannot apply templates to unparsed (escaped or CDATA) text. See some previous answers that may be relevant to you:

    Parsing html with xslt

    XSLT: Reading a param that's an xml document passed as a string

    how to parse the xml inside CDATA of another xml using xslt?

    0 讨论(0)
提交回复
热议问题