xslt&xpath:直接匹配前面的注释

Jos*_*son 3 xml xslt xpath

我试图将XSLT转换应用于一批XML文档.转换的要点是重新排序几个元素.我希望保留任何直接位于元素之前的注释:

<!-- not this comment -->
<element />

<!-- this comment -->
<!-- and this one -->
<element />
Run Code Online (Sandbox Code Playgroud)

我最接近解决方案的是使用表达式:

<xsl:template match="element">
    <xsl:copy-of select="preceding-sibling::comment()"/>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

它收集了太多评论:

<!-- not this comment -->
<!-- this comment -->
<!-- and this one -->
Run Code Online (Sandbox Code Playgroud)

我理解为什么前面提到的XPath无法正常工作,但我对如何进行没有任何好的想法.我正在寻找的是选择所有前面的注释,其后续兄弟是另一个注释或正在处理的当前元素:

preceding-sibling::comment()[following-sibling::reference_to_current_element() or following-sibling::comment()]
Run Code Online (Sandbox Code Playgroud)

Tom*_*lak 5

<xsl:template match="element">
  <xsl:copy-of select="preceding-sibling::comment()[
    generate-id(following-sibling::*[1]) = generate-id(current())
  "/>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

更高效:

<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>
Run Code Online (Sandbox Code Playgroud)