2009-09-22 112 views
0

在XSLT 2.0中,是否有一種簡單的方法來替換字符串中的指定佔位符?XSLT字符串替換

我想的有點像Python的string.Template,在這裏你可以這樣做:

d = dict(name='Joe', age='50') 
print Template("My name is $name and my age is $age").substitute(d) 

點是外部的字符串,因此它可以很容易地改變。到目前爲止,我發現的唯一方法是使用帶參數的命名xsl:模板,但這非常冗長。有更容易的方法嗎?

+0

你的問題不清楚。你是否想要一個自動化機制,以替換值表的形式查找標記,例如$ name,查找「name」,並用值替換$ name?在特定的文本節點?在全球範圍內? – 2009-09-22 21:07:59

+0

我正在尋找可以調用的東西,並將其傳遞給特定的字符串和一組參數。 – 2009-09-22 21:50:16

回答

1

最後我做這樣的事情:

<!-- Reusable template to perform substitutions on a string --> 
<xsl:template name="substitutions"> 
    <!-- "string" is a string with placeholders surrounded by {} --> 
    <xsl:param name="string" /> 
    <!-- "subs" is a list of nodes whose "key" attributes are the placeholders --> 
    <xsl:param name="subs" /> 
    <xsl:analyze-string select="$string" regex="\{{(.*?)\}}"> 
     <xsl:matching-substring> 
      <xsl:value-of select="$subs/sub[@key=regex-group(1)]" /> 
     </xsl:matching-substring> 
     <xsl:non-matching-substring> 
      <xsl:value-of select="." /> 
     </xsl:non-matching-substring> 
    </xsl:analyze-string> 
</xsl:template> 

<!-- Example use of template --> 
<xsl:variable name="nameStr">My name is {name} and my age is {age}</xsl:variable> 
<xsl:call-template name="substitutions"> 
    <xsl:with-param name="string" select="$nameStr" /> 
    <xsl:with-param name="subs"> 
     <sub key="name">Joe</sub> 
     <sub key="age">50</sub> 
    </xsl:with-param> 
</xsl:call-template> 

我不得不使用屬性的替代名稱,而不是僅僅通過節點以不同的名稱(例如<名>喬< /名稱>)。 XPath(或者至少Saxon,我正在使用的處理器)似乎不允許像「$ subs/regex-group(1)」這樣的動態表達式。但它確實允許「$ subs/sub [@key = regex-group(1)]」。

1

沒有的Python字符串模板級的高層次功能,但你可以使用XSL做同樣的事情:分析串,你可以同時處理這將讓一個字符串的正則表達式分析一塊。如果您希望替換爲表驅動,您可以設置一個xsl:鍵來存儲映射,然後編寫一個xsl:函數來對任意字符串執行替換。

不是世界上最簡單的事情,但如果做得正確的話,它肯定是可行和可重用的。

+0

使用analyze-string的好主意 - 查看我的解決方案,發佈爲單獨的答案。 – 2009-09-22 23:10:39