Xml xslt问题-选择直到前面的同级更改

Xml xslt问题-选择直到前面的同级更改,xml,xslt,xpath,Xml,Xslt,Xpath,我知道以前有人问过这个问题,但我正在努力使xpath适合我的场景: 我希望为给定客户获得正确的用户: <root> <div> <span>customer1</span> </div> <div><img></img></div> <div>userForCustomer1</div> <div>anotherUserForCustomer1<

我知道以前有人问过这个问题,但我正在努力使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>
给我们

<div>userForCustomer2</div>

<div>anotherForCustomer2</div>

<div>
<span>customer3</span>
<div>
<img/>
</div>
</div>

<div>userForCustomer3</div>

<div>anotherForCustomer3</div>
<div>userForCustomer2</div>
给我们

<div>userForCustomer2</div>

<div>anotherForCustomer2</div>

<div>
<span>customer3</span>
<div>
<img/>
</div>
</div>

<div>userForCustomer3</div>

<div>anotherForCustomer3</div>
<div>userForCustomer2</div>
让我们非常接近这个结果:

<result>
<div>userForCustomer2</div>

<div>anotherForCustomer2</div>

<div>
<span>customer3</span>
<div>
<img/>
</div>
</div>

</result>

userForCustomer2
另一位客户2
顾客3

但是我想我现在需要修剪我不想要的div,比如在

中有img和customer3的div。你的方法几乎是正确的,你只需要看看

preceding-sibling::div[span][1]
(最接近的前一个div-with-a-span)而不是

preceding-sibling::div[1]
(最近的前一个
div
,无论它是否有
span
子级)

但就我个人而言,我会在XSLT中使用一个键将每个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')" />


/div[span='customer2']/following sibling::div[previous sibling::div[span][1]/span='customer2']让我们非常接近customer2另一个customer2 customer3这个答案实际上回答了我遇到的“核心”问题,尽管它没有解决这个“哑巴”问题问题directly@user3545403通过使用
//div[span='customer2']/后面的同级::div[not(*)][前面的同级::div[span][1]/span='customer2'],您可以限制为不包含任何其他元素的
div
。或者对于键方法,使用键匹配
div[not(*)]
而不是
div[not(span)]
@user3545403顺便说一句,您的XML有点不一致-customer1的
img
customer1
之外,但是其他
img
元素在div之内,作为
span
的兄弟。
<xsl:key name="userByCustomer" match="div[not(span)]"
         use="preceding-sibling::div[span][1]/span" />
<xsl:copy-of select="key('userByCustomer', 'customer2')" />