繁体   English   中英

在xpath中没有条件

[英]Not Condition In xpath

我有以下xml:

<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"

假设“ comes inside表示任何级别的父级,您not能将其与ancestor一起使用,以检查节点是否没有特定的父级/祖先:

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

但是,如果您表示immediate parent不应该是test3 ,那么请切换parent ancestor

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM