简体   繁体   English

如果xpath中的条件为真,如何获取元素

[英]How to get an element if a condition is true in xpath

I have an XML file like this: 我有一个像这样的XML文件:

<div class="main">
    <div aria="location">
        ...
    </div>
    <div class="transcript">
        ...
    </div>
</div>

I want to get the div with aria=" location " if there is an element and if there is not an element with that condition get the div with class=" transcript " . 我想获得aria=" location "div ,如果有一个元素,并且如果不存在那个条件的元素,则获取class=" transcript "div I check my XPath in the chrome inspect element tab and I want to work with that. 我在chrome inspect element标签中检查了我的XPath,我想使用它。

You could use XPath: 您可以使用XPath:

(//div[@aria='location']|//div[@class='transcript' and not(following::div[@aria='location'])])[1]

Explanation: 说明:

  • ( grouping (分组
    • //div[@aria='location'] find a div element with an aria attribute value location //div[@aria='location']查找具有aria属性值locationdiv元素
    • | or 要么
    • //div[@class='transcript' and not(following::div[@aria='location'])] find a div element with a class attribute value transcript and there is no div element with an aria attribute value location after it, in document order //div[@class='transcript' and not(following::div[@aria='location'])]找到一个div与元素class属性值transcript ,并且没有div与元素aria属性值location后它,按文档顺序
  • ) end grouping )结束分组
  • [1] take the first result [1]取得第一个结果

the following check is necessary, because if we just used: following检查是必要的,因为如果我们刚使用过:

(//div[@aria='location']|//div[@class='transcript])[1]

then, if the div element with class transcript came before the div with aria location in document order, then the div with class transcript would be returned due to how XPath traversal works. 然后,如果按文档顺序将具有类transcriptdiv元素排在具有aria locationdiv之前,则由于XPath遍历的工作原理,将返回具有类transcriptdiv

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

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