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」要素内の属性「country」の位置を見つけたい。

<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 に答える