2012-11-19 84 views
1

的,我有以下XML:XSLT - Occurence属性

<Books> 
<Book author="John" country="Norway"/> 
<Book author="Paul" />  
<Book author="Steve" country="England"/>  
</Books> 
<Books>  
<Book author="George" />  
<Book author="Thomas" country="Germany"/> 
</Books> 

我想找到属性“国家”的每个“书”元素内的位置。

<Books> 
<Book author="John" country="Norway"/> --1 
<Book author="Paul" />  
<Book author="Steve" country="England"/> --2 
<Book author="Bob" country="Denmark"/> --3 
</Books> 
<Books>  
<Book author="George" />  
<Book author="Thomas" country="Germany"/> --1 
</Books> 

我们可以使用哪种XPath函数?

回答

3

你可以指望与属性前面的兄弟姐妹的数量,这里是显示一个模板:

<xsl:stylesheet 
    version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

<xsl:template match="Books/Book[@country]"> 
    <xsl:value-of select="count(preceding-sibling::Book[@country]) + 1"/> 
</xsl:template> 

</xsl:stylesheet> 
+0

非常感谢,像魅力一样工作。 –

0

您可以使用XPath计数功能:

count(/Books/Book/@country) 
+0

“计数” 返回 “国” 出现的总次数。我想知道这个属性的位置。 –

+0

@saravana_pc - count是一个汇总函数。不能使用汇总功能检索位置。 – randominstanceOfLivingThing

+0

@Suresh - 我同意不能使用“count”。因此想知道如何解决这个问题。 –

1
<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:template match="Books"> 
    <xsl:apply-templates select=".//@country"/> 
</xsl:template> 

<xsl:template match="@country"> 
    <xsl:value-of select="position()"/> 
    <xsl:text>&#xA;</xsl:text> 
</xsl:template> 
</xsl:stylesheet> 

当此转换应用于提供的XML文档(制作完好):

<t> 
<Books> 
<Book author="John" country="Norway"/> --1 
<Book author="Paul" /> 
<Book author="Steve" country="England"/> --2 
<Book author="Bob" country="Denmark"/> --3 
</Books> 
<Books> 
<Book author="George" /> 
<Book author="Thomas" country="Germany"/> --1 
</Books> 
</t> 

想要的,正确的结果产生

1 
2 
3 
1