xslt & xpath: match directly preceding comments

后端 未结 2 1970
無奈伤痛
無奈伤痛 2021-01-20 22:56

I am attempting to apply an XSLT transformation to a batch of XML documents. The main point of the transform is to re-order several elements. I wish to preserve any comments tha

相关标签:
2条回答
  • 2021-01-20 23:36

    I think the best way of putting it would be as follows:

    I want the preciding comments but only those with the current node as the first element to follow them.

    Then, in xpath1.0/xslt1.0:

    <xsl:template match="element">
    <xsl:copy-of select="preceding-sibling::comment()[count(following-sibling::*[1]|current()) = 1]"/>
    </xsl:template>
    
    0 讨论(0)
  • 2021-01-20 23:56
    <xsl:template match="element">
      <xsl:copy-of select="preceding-sibling::comment()[
        generate-id(following-sibling::*[1]) = generate-id(current())
      ]"/>
    </xsl:template>
    

    More efficient:

    <xsl:key 
      name  = "kPrecedingComment" 
      match = "comment()" 
      use   = "generate-id(following-sibling::*[1])" 
    />
    
    <!-- ... -->
    
    <xsl:template match="element">
      <xsl:copy-of select="key('kPrecedingComment', generate-id())" />
    </xsl:template>
    
    0 讨论(0)
提交回复
热议问题