2012-10-31 51 views
1

具有值的节点的索引列表;如何使用xpath获取使用xpath

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

欲使用类似 /a/b来得到以下结果[。= '真']。对于像 2,5(作为对2集合中的结果位置() 位置)

+0

最终做了一个xslt,在所有事情上打了一个ID,所以这个问题变得微不足道了。 –

回答

1

I.的XPath 1.0溶液

使用

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

这产生第一b元件的其字符串值是 “真” 的位置:

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 every b , 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 
0

语言的基本(&工作)的方法:

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)