[英]How to compare two comma-separated lists and removing matching values using XSLT 1.0
我有兩個包含逗號分隔值的變量:
<xsl:variable name="Include-Cities" select="'London, Paris, Washington, Tokyo'"/>
<xsl:variable name="Exclude-Cities" select="'Paris, Tokyo'"/>
我需要刪除$Include-Cities
中與$Exclude-Cities
找到的值匹配的值,因此以某種方式我要從$Include-Cities
變量中減去這些值並輸出結果。
我環顧了網上,發現以下示例提供了搜索和替換功能,並且如果$ Exclude-Cities中的城市順序與$ Include-Cities中的順序匹配,則該示例有效,但如果值的順序不同則失敗。
我很困,因為兩個列表中的值每天都會更改,我永遠也不知道這些值是什么,因此我認為執行排序(如果可能的話)不會起作用。
我發現的例子:
<xsl:template name="replace-string">
<xsl:param name="text"/>
<xsl:param name="replace"/>
<xsl:param name="with"/>
<xsl:choose>
<xsl:when test="contains($text,$replace)">
<xsl:value-of select="substring-before($text,$replace)"/>
<xsl:value-of select="$with"/>
<xsl:call-template name="replace-string">
<xsl:with-param name="text" select="substring-after($text,$replace)"/>
<xsl:with-param name="replace" select="$replace"/>
<xsl:with-param name="with" select="$with"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
然后我使用以下模板調用模板:
<xsl:call-template name="replace-string">
<xsl:with-param name="text" select="$Include-Cities"/>
<xsl:with-param name="replace" select="$Exclude-Cities" />
<xsl:with-param name="with" select="''"/>
</xsl:call-template>
我還查看了將值標記化並以這種方式進行比較的示例,但一點都不高興。
我知道2.0中提供了字符串比較功能,但僅限於使用XSLT 1.0。
我是XSLT新手,所以有人可以幫忙嗎?
非常感激任何的幫助
我還查看了將值標記化並以這種方式進行比較的示例,但一點都不高興。
令牌化是此處采取的正確方法。 如果您的處理器支持EXSLT str:tokenize
擴展功能,則可以執行以下操作:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:str="http://exslt.org/strings"
extension-element-prefixes="str">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="Include-Cities" select="'London, Paris, Washington, Tokyo'"/>
<xsl:variable name="Exclude-Cities" select="'Paris, Tokyo'"/>
<xsl:template match="/">
<xsl:variable name="incl" select="str:tokenize($Include-Cities, ', ')"/>
<xsl:variable name="excl" select="str:tokenize($Exclude-Cities, ', ')"/>
<output>
<xsl:copy-of select="$incl[not(.=$excl)]"/>
</output>
</xsl:template>
並得到:
結果
<?xml version="1.0" encoding="UTF-8"?>
<output>
<token>London</token>
<token>Washington</token>
</output>
否則,您將必須使用遞歸命名模板進行標記,將結果轉換為節點集,然后進行比較,如上所示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.