1

以下を使用します。

    <a>
  <b>false</b> 
  <b>true</b> 
  <b>false</b> 
  <b>false</b> 
  <b>true</b> 
  </a>

/a/b[.='true'].position() のような結果を 2,5 のようなものを使用して次の結果を取得したい (2 つの位置のコレクションのように)

4

2 に答える 2

1

I. XPath 1.0 ソリューション:

使用:

count(/*/*[.='true'][1]/preceding-sibling::*)+1

これにより、b文字列値が「true」である最初の要素の位置が生成されます。

2

同様の式の評価を繰り返します。ここで、は、... などに[1]置き換えられます。[2]count(/*/*[.='true'])

XSLT ベースの検証:

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

 <xsl:template match="/">
   <xsl:for-each select="/*/*[.='true']">
    <xsl:variable name="vPos" select="position()"/>

    <xsl:value-of select=
     "count(/*/*[.='true'][$vPos]
               /preceding-sibling::*) +1"/>
    <xsl:text>&#xA;</xsl:text>
   </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

この変換が提供された XML ドキュメントに適用されると、次のようになります。

<a>
    <b>false</b>
    <b>true</b>
    <b>false</b>
    <b>false</b>
    <b>true</b>
</a>

The XPath expression is constructed and evaluated for everyb , whose string value is"真" . The results of these evaluations are copied to the output:

2
5

Ⅱ.XPath 2.0 ソリューション:

使用:

index-of(/*/*, 'true')

XSLT 2.0 ベースの検証:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:template match="/">
   <xsl:sequence select="index-of(/*/*, 'true')"/>
 </xsl:template>
</xsl:stylesheet>

この XSLT 2.0 変換が同じ XML ドキュメント (上記) に適用されると、XPath 2.0 式が評価され、この評価の結果が出力にコピーされます

2 5
于 2012-10-31T02:15:05.820 に答える
0

A basic (& working) approach in language :

from lxml import etree
root = etree.XML("""
<a>
  <b>false</b> 
  <b>true</b> 
  <b>false</b> 
  <b>false</b> 
  <b>true</b> 
</a>
""")

c = 0
lst = []

for i in root.xpath('/a/b/text()'):
    c+=1
    if i == 'true':
        lst.append(str(c))

print ",".join(lst)
于 2012-10-31T01:18:51.910 に答える