使用XSLT v2.0,如何检查所有选定节点的文本是否与某些参考值匹配?
例如,我选择所有H1
个节点。我想确保所有这些都等于“标题”或“标题”。
我一直在尝试为此创建一个函数:
<xsl:function name="is-valid" as="xs:boolean">
<xsl:param name="seq" as="item()*" />
<xsl:for-each select="$seq">
<xsl:if test="not(matches(current()/text(),'The title|A heading'))">
<!-- ??? -->
</xsl:if>
</xsl:for-each>
</xsl:function>
我不认为这是XSLT的方法,但我找不到如何做到这一点。
任何提示?
答案 0 :(得分:2)
XSLT 2.0有一个every..satisfies
结构,可以在这里提供帮助:
<xsl:function name="e:is-valid" as="xs:boolean">
<xsl:param name="s" as="item()*" />
<xsl:value-of select="every $i in $s satisfies $i=('The title', 'A heading')"/>
</xsl:function>
这是一个完整的例子:
<?xml version="1.0" encoding="UTF-8"?>
<r>
<h1>Wrong title</h1>
<h1>The title</h1>
<h1>A heading</h1>
</r>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:e="http://example.com/f">
<xsl:template match="/">
<xsl:message>
<xsl:value-of select="e:is-valid(//h1)"/>
</xsl:message>
</xsl:template>
<xsl:function name="e:is-valid" as="xs:boolean">
<xsl:param name="s" as="item()*" />
<xsl:value-of select="every $i in $s satisfies $i=('The title','A heading')"/>
</xsl:function>
</xsl:stylesheet>
答案 1 :(得分:2)
只需使用这个简单的XPath表达式 - the double negation law:
not(h1[not(. = ('The title','A heading'))])
作为演示,给出与@kjhughes:
的答案相同的XML文档<r>
<h1>Wrong title</h1>
<h1>The title</h1>
<h1>A heading</h1>
</r>
这个XSLT 2.0转型:
<xsl:stylesheet version="20" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/*">
<xsl:sequence select="not(h1[not(. = ('The title','A heading'))])"/>
</xsl:template>
</xsl:stylesheet>
产生想要的正确结果:
false
这可以在XPath 1.0中使用,以确定节点集$ns1
的所有字符串值是否属于另一个节点集$ns2
的字符串值:
not(not($ns1[. = $ns2]))
以下是XPath 1,0 / XSLT 1.0等效的XSLT 2.0 / XPath 2.0解决方案:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:param name="pValues">
<v>The title</v>
<v>A heading</v>
</xsl:param>
<xsl:variable name="vValues" select="document('')/*/xsl:param[@name='pValues']/*"/>
<xsl:template match="/*">
<xsl:value-of select="not(h1[not(. = $vValues)])"/>
</xsl:template>
</xsl:stylesheet>