2010-04-21 32 views
6

XSL如何使用XSL爲id中的每個元素生成唯一的id屬性,其中id必須是數字? 下面的XLS工作除了生成的ID是字母數字,我需要數字?XSL numeric generate-id()

<?xml version='1.0' encoding='utf-8'?> 
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' 
    xmlns:msxsl='urn:schemas-microsoft-com:xslt' exclude-result-prefixes='msxsl'> 
    <xsl:output method='xml' indent='yes'/> 
    <xsl:template match='*'> 
     <xsl:copy> 
     <xsl:attribute name='ElementID'> 
      <xsl:value-of select='generate-id()'/> 
     </xsl:attribute> 
     <xsl:apply-templates/> 
     </xsl:copy> 
    </xsl:template>  
</xsl:stylesheet> 

謝謝。

+0

它必須是XSLT 1.0嗎?你能更新到2.0嗎? – topskip 2010-04-21 17:55:06

+0

XSLT 2.0可以。 – gregn 2010-04-21 18:03:29

+0

好問題(+1)。查看我的答案以獲得更高效,更簡單的解決方案。 :) – 2010-04-22 13:18:38

回答

3

切換使用數字()與水平和計數似乎已經完成了。

謝謝

<?xml version='1.0' encoding='utf-8'?> 
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' 
    xmlns:msxsl='urn:schemas-microsoft-com:xslt' exclude-result-prefixes='msxsl'> 
    <xsl:output method='xml' indent='yes'/> 
    <xsl:template match='*'> 
     <xsl:copy> 
     <xsl:attribute name='ElementID'> 
      <xsl:number level='any' count='*' /> 
     </xsl:attribute> 
     <xsl:copy-of select="@*"/><!--copy of existing all attributes--> 
     <xsl:apply-templates/> 
     </xsl:copy> 
    </xsl:template> 
</xsl:stylesheet> 
+0

這是有效的XSLT 1.0,在這種情況下不需要XSLT 2.0。同樣,因爲在你的代碼中你已經改變了XML的版本號,而不是XSLT。 ;-) – markusk 2010-04-22 01:00:54

+0

有斑點的Markusk,2.0被刪除 – gregn 2010-04-22 13:49:04

+0

添加以保留現有屬性 – gregn 2010-04-22 15:53:28

7

您可以隨時使用

 concat(count(ancestor::node()), 
      '00000000', 
      count(preceding::node())) 

懂行的人,如邁克爾·凱警告說<xsl:number/>效率不高,(有時是O(N^2))如果可能的話應該避免。

+0

這也可以,我會關注性能。 – gregn 2010-04-22 13:50:05

+0

你有一個錯位的支架;你可能想要的解決方案是'concat(count(ancestor :: node()),'00000000',count(在:: node()))' – 2012-05-08 23:43:28

+0

@ToddMyhre:謝謝你注意到這一點。現在更正。 – 2012-05-09 01:16:27