[英]How to match a varying number of child elements for parents with the same class using XPath in HTML?
I have a webpage with the following structure, and I'm extracting data from it via XPath Helper Google Chrome extenson 我有一个具有以下结构的网页,并且正在通过XPath Helper Google Chrome扩展程序从中提取数据
<div class="example">
<span class="name">John Doe</span>
<span class="foo">1</div>
</div>
<div class="example">
<span class="name">Jane Doe</span>
</div>
<div class="example">
<span class="name">Richard Roe</span>
</div>
<div class="example">
<span class="name">Jane Roe</span>
<span class="foo">2</div>
</div>
I want to use XPath to select name
and foo
of each example variable. 我想使用XPath选择每个示例变量的
name
和foo
。 If the variable doesn't have a foo
value, it should display me 0
, blank
or NULL
so I can match each name
with each foo
如果该变量没有
foo
值,则应显示0
, blank
或NULL
以便我可以将每个name
与每个foo
匹配
This query //div[@class="example"]/span[@class="name"]
can return all the names 此查询
//div[@class="example"]/span[@class="name"]
可以返回所有名称
John Doe
Jane Doe
Richard Roe
Jane Roe
However with this query //div[@class="example"]/span[@class="foo"]
I only get a result when foo
exists 但是,使用此查询
//div[@class="example"]/span[@class="foo"]
我只有在foo
存在时才得到结果
1
2
With the combination of those two queries alone I can't track which foo
belongs to each name
under the example
div. 单靠这两个查询,我无法在
example
div下跟踪哪个name
属于哪个foo
。
I ideally need a query which returns 我理想上需要一个返回的查询
John Doe, 1
Jane Doe, 0
Richard Roe, 0
Jane Roe, 2
However if I can get a query with only the second part 但是,如果我只能得到第二部分的查询
1
0
0
2
It'd work as well because I could match the results with the respective names. 它也可以正常工作,因为我可以将结果与各自的名称进行匹配。
How do I build a query to do this job with XPath 1.0? 如何使用XPath 1.0建立查询来完成这项工作?
With XPath 2.0 you could use a for loop as : 在XPath 2.0中,您可以使用for循环:
for $ex in //div[@class='example']
return concat( $ex/span[@class='name'], ',', sum($ex/span[@class='foo'], '0'))
It returns : 它返回:
John Doe,1
Jane Doe,0
Richard Roe,0
Jane Roe,2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.