开发者

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

开发者 https://www.devze.com 2022-12-19 04:53 出处:网络
I have the current structure; Item 1 - Subitem 1 - Subitem 2 - Subitem 3 - - Sub subitem 1 - - Sub subitem 2

I have the current structure;

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

I hav开发者_JS百科e 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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消