xslt &xpath:直接匹配前面的注释 [英] xslt & xpath: match directly preceding comments

查看:17
本文介绍了xslt &xpath:直接匹配前面的注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 that directly precede an element:

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

<!-- this comment -->
<!-- and this one -->
<element />

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

The closest I've come to a solution is to use the expression:

<xsl:template match="element">
    <xsl:copy-of select="preceding-sibling::comment()"/>
</xsl:template>

获取太多评论:

<!-- not this comment -->
<!-- this comment -->
<!-- and this one -->

我理解为什么前面提到的 XPath 不能正常工作,但我对如何进行没有任何好的想法.我正在寻找的是选择所有前面的评论,其以下兄弟姐妹是另一个评论或正在处理的当前元素:

I understand why the aforementioned XPath does not work correctly, but I don't have any good ideas on how to proceed. What I'm looking for is something to select all preceding comments whose following-sibling is either another comment or the current element being processed:

preceding-sibling::comment()[following-sibling::reference_to_current_element() or following-sibling::comment()]

推荐答案

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

更高效:

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

这篇关于xslt &amp;xpath:直接匹配前面的注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆