Which should I use: preceding:: or preceding-sibling::?

后端 未结 3 506
深忆病人
深忆病人 2021-01-14 08:28

I\'m hesitating whether to write preceding or preceding-sibling in XSL such as an example xml below.


  

        
3条回答
  •  借酒劲吻你
    2021-01-14 08:59

    It looks to me that you are (also) asking what these axes actually do. As Michael and Har already pointed out, it really depends on the larger picture whether or not to choose one over the other. In practice, the need for preceding, and to a lesser extend preceding-sibling can be a sign of code smell and their performance can be detrimental, depending on input and predicates.

    Let's suppose your input is slightly different:

    
      
        John
      
      
        Sato
        Tanaka
      
      
      
        Ueda
        Suzuki
      
    
    

    1) preceding-sibling::team/staff[1]

    The preceding-sibling axis is a reverse axis, which means it goes from bottom to top through your siblings. The staff step is actually child::staff, which is itself a forward step.

    Here you are asking:

    • take all preceding siblings that match team
    • of all these, go down and select the first staff
    • in the augmented XML, this will select "John"

    2) preceding::staff[2]

    The preceding axis is also a reverse axis, but instead of going over the siblings, it goes over all nodes that have already been passed (meaning: if a node is still in the present ancestor axis, it is not selected), depth first (meaning: text nodes in staff come before staff children, which come before team siblings).

    Here you are asking:

    • take all the preceding nodes that match staff, that is empty, Tanaka, Sato and John (in that order).
    • select the second you find
    • in the augmented XML, this will select Tanaka

    3) ../team[1]/staff[1]

    .. is short for parent::node(). It means take the parent of the current node (which is the root element sales_division)

    Here you are asking:

    • go to the parent sales_division
    • from there go down and find the first child matching team
    • from there find the first child matching staff
    • in the augmented XML, this is John

    So, in conclusion, it depends on the actual XML structure. Typical use-cases for preceding-sibling are where the order of your XML is known and meaningful (for instance, two coordinates, where the previous sibling is longitude, the current is latitude).

    In practice, I see more often that you need an element that is a sibling before or after the current node. In that case, the .. (parent) syntax is probably the best way to go, possibly excluding the current node from the node set. This is easier in XSLT 2.0 and 3.0 than in 1.0.

提交回复
热议问题