XSLT: Get the closest item with a specified value defined? (Sitecore)

巧了我就是萌 提交于 2019-12-11 05:47:00

问题


I have the current structure;

Item 1
 - Subitem 1
 - Subitem 2
 - Subitem 3
 - - Sub subitem 1
 - - Sub subitem 2
 - - Sub subitem 3
 - - etc

I have a field that is only defined on "Item 1". Let's call it 'Header'.

When i am on "Item 1" its easy enough to extract this value, but what about when i am on the other items? Is there a way i can go through the tree (up) until i find a field called 'Header' and it has a value, and then stop and use this as a reference point in my sub items?


回答1:


If you want to look up the tree and find the closest element that contains a Header attribute with a value, something like this should work.

  <xsl:value-of select="(ancestor::*/@Header[.!=''])[last()]" />

This uses the ancestor axis to look up the tree and the xpath expression looks for any element with a Header attribute who's value is not empty.

A second filter is used to evaluate the last one. If there is more than one ancestor that has a @Header with a value, the last one would be the closest to the context node, because the result is in document order.

EDIT: An alternative way to find the same results, leveraging the fact that ancestor axis returns in reverse document order would be to put the filter criteria in the predicate for the ancestor axis step, select the first one(closest match to the context node), and then step into the @Header:

<xsl:value-of select="ancestor::*[@Header!=''][1]/@Header" />



回答2:


If your current context isn't Item 1 but rather one of its children, you can use the ancestor axis to get its data.

So, assuming your Item 1 element has an attribute called Header, you can do something like this:

<xsl:value-of select="ancestor::Item1/@Header"/>

This assumes your XML structure (which you really should have supplied in your question) looks like this:

<Item1 Header="a header">
  <Subitem1/>
  <Subitem2/>
  <!-- etc -->
</Item1>

And that the name "Item1" is unique in this structure.



来源:https://stackoverflow.com/questions/2216567/xslt-get-the-closest-item-with-a-specified-value-defined-sitecore

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!