我知道它之前已经被问到了,但是我正在努力让xpath正确地适应我的场景: 我想获得给定客户的正确用户:
<root>
<div>
<span>customer1</span>
</div>
<div><img></img></div>
<div>userForCustomer1</div>
<div>anotherUserForCustomer1</div>
<div>
<span>customer2</span>
<div><img></img></div>
</div>
<div>userForCustomer2</div>
<div>anotherForCustomer2</div>
<div>
<span>customer3</span>
<div><img></img></div>
</div>
<div>userForCustomer3</div>
<div>anotherForCustomer3</div>
</root>
使用以下xpath,我将获得下一组用户:
//div[span='customer2']/following-sibling::div[preceding-sibling::div/span = 'customer2']
给我们
<div>userForCustomer2</div>
<div>anotherForCustomer2</div>
<div>
<span>customer3</span>
<div>
<img/>
</div>
</div>
<div>userForCustomer3</div>
<div>anotherForCustomer3</div>
如果我试图阻止它走远:
//div[span='customer2']/following-sibling::div[preceding-sibling::div[1]/span = 'customer2']
给我们
<div>userForCustomer2</div>
它只返回1个用户,而不是user2的两个用户
我所追求的是:
<div>userForCustomer2</div>
<div>anotherForCustomer2</div>
我确定这是一个简单的答案。
提前致谢
========================
更新
//div[span='customer2']/following-sibling::div[preceding-sibling::div[span][1]/span= 'customer2']
让我们非常接近这个结果:
<result>
<div>userForCustomer2</div>
<div>anotherForCustomer2</div>
<div>
<span>customer3</span>
<div>
<img/>
</div>
</div>
</result>
但我想我现在需要修剪我不想要的div,例如img和customer3 in
答案 0 :(得分:0)
你的方法几乎是正确的,你只需要看看
preceding-sibling::div[span][1]
(最近的前一个div-with-a-span)而不是
preceding-sibling::div[1]
(最近的div
,无论是否有span
孩子。
但我个人会在XSLT中使用 key 来解决这个问题, key 将每个div-without-a-span链接到其客户名称:
<xsl:key name="userByCustomer" match="div[not(span)]"
use="preceding-sibling::div[span][1]/span" />
现在给定一个特定的客户名称,您可以通过单个函数调用提取所有相关用户
<xsl:copy-of select="key('userByCustomer', 'customer2')" />