[英]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
属性值location
的div
元素 |
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. 然后,如果按文档顺序将具有类
transcript
的div
元素排在具有aria
location
的div
之前,则由于XPath遍历的工作原理,将返回具有类transcript
的div
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.