php - 使用 text() 匹配 XSLT 中的自定义实体名称

标签 php xslt xml-entities

我正在使用 <xsl:template match="m:*/text()">匹配我的 XML 文档中的文本,它适用于纯文本和已知实体,即它适用于像 &amp; 这样的实体或 unicode 实体,如 &#x003C0; .

但是不起作用的是匹配自定义实体名称。例如我有一个实体 &pi;在我的 XML 文档中,应该使用 text() 进行匹配.出于某种原因,它不会将该实体视为文本,这意味着没有任何匹配项。

请注意,我确实在 XML 文档和 XSLT 文档的 Doctype 声明中声明了实体名称:

<!DOCTYPE xsl:stylesheet [<!ENTITY pi "&#x003C0;">]>

text()匹配自定义实体名称的正确方法,还是我需要使用其他函数? (也许我在声明实体名称时也做错了什么?)

谢谢

编辑

XML

<!DOCTYPE mathml [<!ENTITY pi "&#x003C0;">]>
<math xmlns="http://www.w3.org/1998/Math/MathML" display="inline">    
    <mi>&pi;</mi>
    <mi>test</mi>
    <mi>&#x003C0;</mi>
</math>

XSLT

<?xml version='1.0' encoding="UTF-8"?>
<!DOCTYPE xsl:stylesheet [<!ENTITY pi "&#x003C0;">]>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:m="http://www.w3.org/1998/Math/MathML"
                version='1.0'>

    <xsl:template match="m:*/text()">
        <xsl:call-template name="replaceEntities">
            <xsl:with-param name="content" select="normalize-space()"/>
        </xsl:call-template>
    </xsl:template>

    <xsl:template name="replaceEntities">
        <xsl:param name="content"/>
        <xsl:value-of select="$content"/>
    </xsl:template>
</xsl:stylesheet>

变量$content应该打印三次,但只有 test&#x003C0;打印出来。

使用PHP处理

$xslDoc = new DOMDocument();
$xslDoc->load("doc.xsl");
$xslProcessor = new \XSLTProcessor();
$xslProcessor->importStylesheet($xslDoc);
$mathMLDoc = new DOMDocument();
$mathMLDoc->loadXML('<!DOCTYPE mathml [<!ENTITY pi "&#x003C0;">]><math xmlns="http://www.w3.org/1998/Math/MathML" display="inline"><mi>&pi;</mi><mi>test</mi><mi>&#x003C0;</mi></math>');
echo $xslProcessor->transformToXML($mathMLDoc);

最佳答案

据我所知,问题在于 DTD 对于 XSLT 样式表不可见。在转换文档之前,使用以下内容将实体替换为其文本值:

$mathMLDoc->substituteEntities = true;

如在

$xslDoc = new DOMDocument();
$xslDoc->load("tree.xsl");
$xslProcessor = new \XSLTProcessor();
$xslProcessor->importStylesheet($xslDoc);
$mathMLDoc = new DOMDocument();
$mathMLDoc->substituteEntities = true;
$mathMLDoc->loadXML('<!DOCTYPE math [<!ENTITY pi "&#x003C0;">]><math xmlns="http://www.w3.org/1998/Math/MathML" display="inline"><mi>&pi;</mi><mi>test</mi><mi>&#x003C0;</mi></math>');
echo $xslProcessor->transformToXML($mathMLDoc);

会产生

<?xml version="1.0"?>
πtestπ

一些背景:http://php.net/manual/en/xsltprocessor.transformtoxml.php#99932http://hublog.hubmed.org/archives/001854.html .

关于php - 使用 text() 匹配 XSLT 中的自定义实体名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29749851/

相关文章:

html - 使用 XSLT 将 XML 拆分为多个 HTML 文件

javascript - 打印后页面不重新加载

php - mysql 返回错误的整数

php - MySQL中如何设置自增值从1开始?

python - 如何使用 xml.etree 解析外部实体,如 lxml.etree

xml - 在 XSLT 2 中加载实体?

Java 正则表达式 : Replace all xml characters with their entity number

php - 如何显示特定div中的mysql表?

java - XMLStreamException : XML version "1.1" is not supported, 仅支持 XML 1.0

java - 在 XSLT 中调用 Java 方法