使用XSLT枚举同名节点
我有很多 XML 文件,通常多次包含节点(每次都包含不同的数据)。 示例:
<?xml version="1.0" encoding="UTF-8"?>
<SomeName>
<Node>
DataA
</Node>
<Node>
DataB
</Node>
<Node>
DataC
</Node>
<AnotherNode>
DataD
</AnotherNode>
<AnotherNode>
DataE
</AnotherNode>
<AnotherNode>
DataF
</AnotherNode>
<SingleNode>
DataG
</SingleNode>
</SomeName>
所需的输出为:
<?xml version="1.0" encoding="UTF-8"?>
<SomeName>
<Node1>
DataA
</Node1>
<Node2>
DataB
</Node2>
<Node3>
DataC
</Node3>
<AnotherNode1>
DataD
</AnotherNode1>
<AnotherNode2>
DataE
</AnotherNode2>
<AnotherNode3>
DataF
</AnotherNode3>
<SingleNode>
DataG
</SingleNode>
</SomeName>
问题是,我没有所有重复节点名的列表,因此我需要 XSLT 遍历所有节点,并且只对多次存在的节点进行编号。这可能吗?
有人对如何实现这一目标有好主意吗?
谢谢!
I have many many XML files that often contain nodes mutiple times (each time with different data).
Example:
<?xml version="1.0" encoding="UTF-8"?>
<SomeName>
<Node>
DataA
</Node>
<Node>
DataB
</Node>
<Node>
DataC
</Node>
<AnotherNode>
DataD
</AnotherNode>
<AnotherNode>
DataE
</AnotherNode>
<AnotherNode>
DataF
</AnotherNode>
<SingleNode>
DataG
</SingleNode>
</SomeName>
The desired Output would be:
<?xml version="1.0" encoding="UTF-8"?>
<SomeName>
<Node1>
DataA
</Node1>
<Node2>
DataB
</Node2>
<Node3>
DataC
</Node3>
<AnotherNode1>
DataD
</AnotherNode1>
<AnotherNode2>
DataE
</AnotherNode2>
<AnotherNode3>
DataF
</AnotherNode3>
<SingleNode>
DataG
</SingleNode>
</SomeName>
The Problem is, I don't have a list of all the duplicate Nodenames, so I need the XSLT to run through all nodes and only number those that exist multiple times. Is that possible?
Does anyone have a good idea on how to accomplish that?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 count(preceding-sibling::*[name(.) = name(current())]) 来获取与上下文元素同名的前面同级元素的数量,并且
创建与上下文元素同名的元素,并附加字母“n”到它。结合这些事实应该可以让您达到您想要的效果。You can use
count(preceding-sibling::*[name(.) = name(current())])
to get the number of preceding sibling elements with the same name as the context element, and<xsl:element name="concat(name(.),'n')" />
to create an element of the same name as the context element, with the letter 'n' appended to it. Combining these facts should allow you to achieve the effect you desire.这是一个完整的解决方案。 建议使用 Muenchian 方法进行分组,而不是基于
count(preceding::*[someCondition])
进行分组,效率极低 -- O(N^ 2)。此转换:
应用于提供的 XML 文档时:
产生所需的结果:
Here is a complete solution. It is recommended to use the Muenchian method for grouping and not grouping based on
count(preceding::*[someCondition])
, which is grossly inefficient -- O(N^2).This transformation:
when applied on the provided XML document:
produces the wanted result: