首页 > 解决方案 > 使用 XSLT 2.0 的函数 fn:parse-xml-fragment 是否有任何替代方法?

问题描述

我是这个 XSLT 世界的新手,我们有一种情况,我们想使用fn:parse-xml-fragment()XSLT 3.0 版支持的功能。

但是,在我们的框架中,我们仍处于 XSLT 2.0 版,不允许升级saxon.jar到 9.6 版。
但是在 XSLT 2.0 版中,有没有其他方法可以实现与此函数相同的结果?

标签: xmlxsltxslt-2.0

解决方案


该函数是 XPath 3.0/3.1 函数https://www.w3.org/TR/xpath-functions-30/#func-parse-xml-fragment所以您会在支持 XPath 3 的 XSLT 处理器中找到它。取决于您的Saxon 版本和版本 如果您在样式表中使用它可能会使用它version="3.0",即使您有一个不支持最终 XSLT 3.0 规范的 Saxon 版本和/或版本(例如,Saxon 9.8 是第一个主要的 Saxon 版本实现最终的 XSLT 3 规范,但parse-xml-fragment如果您在 XSLT 代码中使用,Saxon 9.7 也支持XPath 3 等函数version="3.0",如果我没记错的话)。

您还没有告诉我们您使用的究竟是哪个处理器和版本,有可能将其作为扩展功能使用或实现。

还有纯 XSLT 2 中的 David Carlisle 的 HTML 解析器https://github.com/davidcarlisle/web-xslt/blob/master/htmlparse/htmlparse.xsl可以用作(或至少被滥用)作为 XML(片段)解析器,如果您false()用于第三个参数,例如样式表

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"
    xmlns:dpc="data:,dpc"
    exclude-result-prefixes="#all">

    <xsl:import href="https://raw.githubusercontent.com/davidcarlisle/web-xslt/master/htmlparse/htmlparse.xsl"/>

    <xsl:output method="html" doctype-public="XSLT-compat" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />

    <xsl:template match="/">
      <html>
        <head>
          <title>New Version!</title>
        </head>
        <xsl:apply-templates/>
      </html>
    </xsl:template>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="section[h2 = 'Test']/ul/li">
        <xsl:copy>
           <xsl:value-of select="count(dpc:htmlparse(., '', false())/node())"/> 
        </xsl:copy>
    </xsl:template>

</xsl:transform>

http://xsltransform.hikmatu.com/948Fn5t/2在用作输入的片段中找到正确数量的子节点(例如

        <li><![CDATA[<foo>foo 1</foo><bar>bar 1</bar><foo>foo 2</foo>]]></li>
        <li><![CDATA[text<element/>text<element>...</element>text]]></li>

计数 3 和 5 个节点),这与在撒克逊 9.8的https://xsltfiddle.liberty-development.net/eiZQaFHparse-xml-fragment中所做的相同。

但是,您会发现该htmlparse函数可能会解析格式错误的标记,而该parse-xml-fragment函数会给您一个错误,因为任何不遵循外部解析实体的 XML 规则。


推荐阅读