将转换应用于包含转义 HTML 的 XML 属性 [英] Apply transforms to XML attribute containing escaped HTML

查看:24
本文介绍了将转换应用于包含转义 HTML 的 XML 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些像这样的 XML:

I have some XML that looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<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>

如您所见,comment 节点中的 text 属性包含转义的 HTML.我想将属性的内容作为 XHTML 获取,我目前在模板中使用:

As you can see, the text attribute in the comment node contains escaped HTML. I would like to get the contents of the attribute as XHTML, which I currently do this inside a template using:

<xsl:value-of select="@text" disable-output-escaping="yes" />

这让我得到了最终输出中的 HTML:

That gets me the HTML in the final output:

<div class="wiki text"><h4>Tom Fenech</h4>Here is a comment</div>

但我希望能够提取 <h4> 标记的内容以在其他地方使用.一般来说,一旦它被转义,能够操纵它的内容会很好.

But I want to be able to extract the contents of the <h4> tag to use elsewhere. In general, it would be nice to be able to manipulate the contents of this once it has been escaped.

如何将更多模板应用到 的输出?

How do I apply further templates to the output of the <xsl:value-of />?

我目前正在使用 PHP 内置 XSLT 处理器,它支持XSLT 1.0 版,但如果较新版本的功能使这成为可能,我愿意考虑使用替代处理器.

I am currently using the PHP built-in XSLT processor, which supports XSLT version 1.0, although I would be willing to consider using an alternative processor if features from newer versions make this possible.

推荐答案

这里有一种方法可以做到,从 XSLT 调用 PHP 函数:

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);

这篇关于将转换应用于包含转义 HTML 的 XML 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆