是否可以使用正则表达式通过 XSLT 搜索 XML 内容?我可以使用包含搜索节点,但是我需要使用单词边界(例如 /\bmy phrase\b/i
)来搜索短语,而不仅仅是单个单词。
当使用以下搜索“blood pressure”时,将返回所有包含“blood”、“pressure”和“blood pressure”的节点。
我只想返回包含“血压”的节点。使用 PHP preg_match,我可以通过以下方式实现:/\b$keywords\b/i
<xsl:template match="//item">
<xsl:choose>
<xsl:when test="contains(translate(title, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), $keyword) or contains(translate(content, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), $keyword)">
<item>
<title><xsl:value-of select="title"/></title>
<content><xsl:value-of select="content"/></content>
<date><xsl:value-of select="date"/></date>
<author><xsl:value-of select="author"/></author>
</item>
</xsl:when>
</xsl:choose>
</xsl:template>
最佳答案
我。你可以在 XSLT 2.0 中做这样的事情:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="s">
<xsl:variable name="vWords" select=
"tokenize(lower-case(string(.)),
'[\s.?!,;—:\-]+'
) [.]
"/>
<xsl:sequence select=
" for $current in .,
$i in 1 to count($vWords)
return
if($vWords[$i] eq 'blood'
and
$vWords[$i+1] eq 'pressure'
)
then .
else ()
"/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
当此 XSLT 2.0 转换应用于以下 XML 文档时(问题中未提供此类文档!!!):
<t>
<s>He has high blood pressure.</s>
<s>He has high Blood Pressure.</s>
<s>He has high Blood
Pressure.</s>
<s>He was coldblood Pressured.</s>
</t>
所需的正确结果(仅生成包含“blood”和“pressure”(不区分大小写且作为两个相邻词)的元素:
<s>He has high blood pressure.</s>
<s>He has high Blood Pressure.</s>
<s>He has high Blood
Pressure.</s>
解释:
使用
tokenize()
函数拆分 nn 字母字符的字符串,并带有不区分大小写和多行模式的标志。遍历
tokenize()
的结果以找到一个“blood”
词,紧接着是一个“pressure”
词.
二。 XSLT 1.0 解决方案:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="vUpper" select=
"'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
<xsl:variable name="vLower" select=
"'abcdefghijklmnopqrstuvwxyz'"/>
<xsl:variable name="vSpaaaceeees" select=
"' '
"/>
<xsl:variable name="vAlpha" select="concat($vLower, $vUpper)"/>
<xsl:template match="s">
<xsl:variable name="vallLower" select="translate(., $vUpper, $vLower)"/>
<xsl:copy-of select=
"self::*
[contains
(concat
(' ',
normalize-space
(translate($vallLower, translate($vallLower, $vAlpha, ''), $vSpaaaceeees)),
' '
),
' blood pressure '
)
]
"/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
当这个转换应用于同一个 XML 文档时(如上),产生相同的正确结果:
<s>He has high blood pressure.</s>
<s>He has high Blood Pressure.</s>
<s>He has high Blood
Pressure.</s>
解释:
正在转换为小写。
使用双重翻译方法将任何非字母字符替换为空格。
然后使用
normalize-space()
将任意一组相邻空格替换为单个空格。然后用空格围绕这个结果。
最后,验证当前结果是否包含字符串
"blood pressure "
。
关于php - XSLT 使用正则表达式、单词边界搜索 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9656082/