使用 XSLT 1.0 包装标头的同级元素
我正在使用 PHP 中的 XSLT 1.0,并且希望将标题 (h2) 之后的所有同级元素包装到 div 中,以便我可以切换它们。
输入看起来像这样
...
<h2>Nth title</h2>
<first child>...</first child>
...
<last child>...</last child>
<h2>N+1st title</h2>
...
,输出应该是
...
<h2>Nth title</h2>
<div>
<first child>...</first child>
...
<last child>...</last child>
</div>
<h2>N+1st title</h2>
...
Is there a way to do this in XSLT 1.0?
I'm working with XSLT 1.0 from PHP and want to wrap all the sibling elements after a heading (h2) into a div so I can toggle them.
The input would look like
...
<h2>Nth title</h2>
<first child>...</first child>
...
<last child>...</last child>
<h2>N+1st title</h2>
...
and the output should be
...
<h2>Nth title</h2>
<div>
<first child>...</first child>
...
<last child>...</last child>
</div>
<h2>N+1st title</h2>
...
Is there a way to do this in XSLT 1.0?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此转换:
应用于此 XML 文档时:
产生所需的正确结果:
说明:
身份规则/模板“按原样”复制每个节点。
h2
元素的身份规则被覆盖。这里的操作是复制h2
元素,然后输出一个div
并在其中将模板(在特殊模式下)应用到所有节点(不是>h2
本身),其中此h2
元素是第一个前同级h2
元素。要在上一步中包含的节点可以方便地定义为
指令。为了阻止
div
中包裹的节点被身份规则再次输出,我们提供了一个匹配此类节点的模板,该模板会简单地忽略它们。This transformation:
when applied on this XML document:
produces the wanted, correct result:
Explanation:
The identity rule/template copies every node "as-is".
The identity rule is overriden for
h2
elements. Here the action is to copy theh2
element and then to output adiv
and inside it to apply templates (in a special mode) to all nodes (that are noth2
themselves) for which thish2
element is the first preceding-siblingh2
element.The nodes to include in the previous step are conveniently defined as an
<xsl:key>
instruction.In order to stop the nodes that are wrapped in
div
to be output again by the identity rule, we provide a template matching such nodes, that simply ignores them.是的。制作一个匹配h2元素的模板;在该模板中,您可以使用以下 xpath 表达式选择下一个 h2 之前的所有以下同级:
following-sibling::*[count(preceding-sibling::h2[1] | current()) = 1].
Yes. Make a template that matches h2 elements; within that template, you can select all following siblings before the next h2 using this xpath expression:
following-sibling::*[count(preceding-sibling::h2[1] | current()) = 1]
.