在 xml 层次结构中向上移动分隔符元素
我有一个 xml 文档,其分隔符位于层次结构深处。
<A>
<B>
<C id='1'/>
<separator/>
<C id='2'/>
</B>
<B>
<C id='3'/>
<separator/>
</B>
<B>
<C id='4'/>
</B>
</A>
我想向上移动分隔符,保持元素有序。所以所需的输出是
<A>
<B>
<C id='1'/>
</B>
</A>
<separator/>
<A>
<B>
<C id='2'/>
</B>
<B>
<C id='3'/>
</B>
</A>
<separator/>
<A>
<B>
<C id='4'/>
</B>
</A>
How can it be done using xslt 1.0 only?可以不使用for-each
而仅使用模板匹配来完成吗?
更新: 我实际上得到了 4 个不同程度的通用性的精彩答案,谢谢你们。
I have an xml document with separators deep down in the hierarchy.
<A>
<B>
<C id='1'/>
<separator/>
<C id='2'/>
</B>
<B>
<C id='3'/>
<separator/>
</B>
<B>
<C id='4'/>
</B>
</A>
I want to move the separators upwards, keeping elements in order. So the desired output is
<A>
<B>
<C id='1'/>
</B>
</A>
<separator/>
<A>
<B>
<C id='2'/>
</B>
<B>
<C id='3'/>
</B>
</A>
<separator/>
<A>
<B>
<C id='4'/>
</B>
</A>
How can it be done using xslt 1.0 only? Can it be done without for-each
, using template match only?
UPDATE:
I actually got 4 brilliant answers of different levels of generality, thank you, guys.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此转换:
应用于提供的 XML 文档时:
产生所需的正确结果:
This transformation:
when applied on the provided XML document:
produces the wanted, correct result:
此样式表:
输出:
注意:按
分隔符
分组,为可能的C
添加最后一个第三级元素,而不跟随分隔符
>。编辑:更多拉样式,更多架构不可知论,此样式表:
编辑2:更通用的解决方案(我不信任的一件事,ja!)
注意:主要是细粒度的遍历。底层层次结构规则(在本例中为根元素)复制自身和分隔符(最后一组没有后续分隔符的虚拟节点)传递余数分隔符以处理第一个子级,并具有足够的后续分隔符来处理。修改后的细粒度遍历身份规则,复制自身并再次处理第一个子级和后续兄弟级,并具有足够的后续分隔符来处理。最后,分隔符规则打破了这个过程。
编辑3:其他更通用的解决方案,现在具有递归身份规则
编辑4:现在与以前相同,但使用键测试而不是节点集交集。
This stylesheet:
Output:
Note: Grouping by following
separator
, adding last third level element for posibleC
without followingseparator
.Edit: More pull style, more schema agnostic, this stylesheet:
EDIT 2: More general solution (one thing I do not trust, ja!)
Note: Mostly a fine grained traversal. A floor hierarchy rule (in this case root element) copying itself and separator (dummy node for last group without following separator) passing remainder separators to process first child with enough following separators to process. A modified fine grained traversal identity rule, copying itself and again processing first child and following sibling with enough following separators to process. At last, a separator rule breaking the process.
Edit 3: Other more general solution, now with recursive identity rule
Edit 4: Now just the same as before but with key test instead of node set intersection.