1

我有以下xml:

<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 函数?

4

3 回答 3

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>
于 2012-11-19T16:54:25.937 回答
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
于 2012-11-19T16:59:11.490 回答
0

您可以使用 XPath 计数功能:

count(/Books/Book/@country)
于 2012-11-19T16:47:42.623 回答