2014-12-13 52 views
2

我有以下XML:没有条件在XPath

<test1> 
    <test2> 
     <text>This is a question on xpath 
     </text> 
    </test2> 
    <test3> 
     <test2> 
      <text>Do not extract this 
      </text> 
     </test2> 
    </test3> 
</test1> 

我需要内test2/text提取文本但如果test2来自内部test3。这怎么能在xpath中完成?我试着用findall的东西,如:

for p in lxml_tree.xpath('.//test2',namespaces={'w':w}): 
    for q in p.iterancestors(): 
     if q.tag=="test3": 
      break 
     else: 
      text+= ''.join(t.text for t in p.xpath('.//text')) 

但这不起作用。我猜想xpath在单个表达式中有一个更好的方法来排除它。

预期输出:

text = "This is a question on xpath" 

回答

3

通过comes inside假设你是父母的任何级别,就可以使用notancestor axis检查,看节点是否不具有特定的父/祖先:

//test2[not(ancestor::test3)]/text 

然而,如果你的意思immediate parent不应该test3,然后切换ancestorparent

//test2[not(parent::test3)]/text 
+0

很好,工作!这可以在findall中使用吗? – 2014-12-13 09:31:47

+0

我不是pythonista,但结果是一个'nodeset',而lxml似乎是一个健壮的库,所以我可以想象这可以在lxml_tree.xpath('.// test2 [not(ancestor: :TEST3)] /文本')' – StuartLC 2014-12-13 09:34:27