2017-06-20 17 views
0

我有以下結構的網頁,和我通過XPath的助手谷歌瀏覽器extenson如何使用HTML中的XPath爲父母的相同類匹配不同數量的子元素?

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

我想使用XPath來選擇name每個例如可變的foo提取它的數據。如果變量沒有foo值,它應該顯示我0blankNULL,所以我可以相互匹配name每個foo

該查詢//div[@class="example"]/span[@class="name"]可以返回所有的名字

John Doe 
Jane Doe 
Richard Roe 
Jane Roe 

然而,隨着此查詢//div[@class="example"]/span[@class="foo"]我只得到一個結果,當foo存在

1 
2 

以T他單獨組合這兩個查詢我無法跟蹤哪個foo屬於下的example div。

我非常需要一個查詢返回

John Doe, 1 
Jane Doe, 0 
Richard Roe, 0 
Jane Roe, 2 

但是,如果我能得到一個查詢只與第二部分

1 
0 
0 
2 

它會工作,以及因爲我可以匹配的結果各自的名字。

如何使用XPath 1.0構建查詢來完成這項工作?

回答

0

在XPath 2.0,你可以使用一個for循環:

for $ex in //div[@class='example'] 
return concat($ex/span[@class='name'], ',', sum($ex/span[@class='foo'], '0')) 

它返回:

John Doe,1 
Jane Doe,0 
Richard Roe,0 
Jane Roe,2 
+0

對於這個任務,我將使用Chrome擴展的XPath助手。我沒有找到文檔來確保它支持哪個XPath版本。但是由於你的功能不起作用,我認爲它只適用於XPath 1.0 – steps

+0

@steps是來自網頁的html嗎? – SomeDude

+0

是的,這是一個網頁 – steps

相關問題